0

I have the following code:

let date1 = new Date("January 13, 2018 11:00:00");
console.log(date1.getTime());

console.log(typeof date1.getTime() === Number);
console.log(typeof date1.getTime());
console.log(typeof date1.getTime() === number);

Which prints:

1515841200000
false
number
ReferenceError: number is not defined
    at eval:31:40
    at eval
    at new Promise

So it looks like typeof date1.getTime() is number. However, when I test the equality with number I get an error, and when I test the equality with Number I get false.

The reason I want to test the type is that I have a Jest test, where I am checking if a variable is a Number:

expect.any(Number)

However, the test gets a variable from a statement like date1.getTime() and the test is failing instead of passing.

So how could I test the type such that date1.getTime() would not make the test fail?

3
  • 1
    console.log(typeof date1.getTime() === 'number');returns true.
    – hisener
    Commented Jan 21, 2018 at 12:26
  • 1
    How are you using expect.any(Number)? According to the docs "You can use it inside toEqual or toBeCalledWith"
    – Ivar
    Commented Jan 21, 2018 at 12:31
  • I'm using it inside toEqual
    – bsky
    Commented Jan 21, 2018 at 14:04

2 Answers 2

0

console.log(typeof date1.getTime() === 'number') since typeof operator returns a string.

Please refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

You can use this in your assertion: expect(typeof date1.getTime()).toBe('number')

1
  • 1
    What about expect(typeof date1.getTime()).toBe('number'); ?
    – hisener
    Commented Jan 21, 2018 at 12:31
0

You can use:

expect(date1.getDate()).toEqual(expect.any(Number));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.