40

I have a test as follows:

expect(result.data.quota).toBeInstanceOf(Number);

This test fails with a weird error saying the a Number was expected and a Number was received:

 expect(value).toBeInstanceOf(constructor)

    Expected constructor: Number
    Received constructor: Number
    Received value: 2000
skyboyer
  • 22,209
  • 7
  • 57
  • 64

4 Answers4

46

expect(value).not.toBeNaN();

Edit: I would go with @bszoms solution:

expect(typeof value).toBe('number')
Reynicke
  • 1,407
  • 1
  • 11
  • 21
  • 8
    This is wrong. False is not NaN but also not a number, for example. – Marcos Pereira Apr 23 '19 at 17:00
  • 3
    This answer must clearly be avoided. This will make your tests successful for *ANYTHING* but NaN. `false`, `"some string"`, `true`, `Promise`, `ReactComponent` you name it – Lukas Sep 04 '19 at 16:09
44

The following works for all constructors:

expect(value).toEqual(expect.any(Number));
stephan
  • 655
  • 1
  • 7
  • 11
24

You can also do this: expect(typeof <value>).toBe('number')

Or you can use jest-extended, which adds a whole range of matchers including toBeNumber.

Both courtesy of the discussion here.

maltem-za
  • 1,225
  • 2
  • 16
  • 23
2

Taking @stephan's anwer, this works for async / promise based methods:

await expect(asyncFunction()).resolves.toEqual(expect.any(Number));
Lukas
  • 9,752
  • 15
  • 76
  • 120