I have the following code:
it('it should return a float number', async () => {
const exchangeRate = await getExchangeRate('USD','HUF')
expect(exchangeRate).toBe()
})
How can I build this test so that I can use the expect()
method to check if the exchangeRate
const is a float number or just a number ? ....
CodePudding user response:
If you are using React Jest, you can try using expect().toBeInstanceof(class). so inside expect, you put the object you want to check and where it says class, what value to expect (ex. .toBeInstanceOf(Date)). Here is some documentation that might help.
CodePudding user response:
You can assert the type of the value by using typeof
:
expect(typeof exchangeRate === 'number').toBe(true)
CodePudding user response:
You can assert on the following
expect(Number.isInteger(exchangeRate)).toBe(true); // This will be true if its a Integer else it will be false for float.
To further add some more checks you can do the following:
expect(!isNaN(exchangeRate) && Number.isInteger(exchangeRate)).toBe(true); // Check for Integer
expect(!isNaN(exchangeRate) && !Number.isInteger(exchangeRate)).toBe(true); // Check for Float
CodePudding user response:
In javascript there is only 1 numeric type: number
. Both int (whole) values and float (fractional) values are stored using the number
type.
It is possible to check if a number is a whole value by using Number.isInteger(x)
, however this will return true also if your float happens to be 3.00000....
- which is a totally valid float value, while also being exactly the same as the "integer" value 3
.
In this case you probably would want to use typeof x == 'number' && !isNaN(x)
which will return true for all "float" values, inclusing for those values that happen to be "integer" values.