Spy on global date has very weird behaviors
See original GitHub issueHello,
I have some test where I need to control what new Date
returns, so I went through the way of spy on global.date. However, it is not honouring the implementation very well, and the behavior I’m getting is quite strange.
If I go with this simple implementation:
const mockDate = jest.spyOn(global, 'Date');
mockDate.mockImplementation(x => x );
What I get as output is just an empty object instead of the symbol I’m passing into it. For some reason, changing the implementation to something like this, makes it work (in some situations)
const mockDate = jest.spyOn(global, 'Date');
mockDate.mockImplementation(x => ({date: x}) );
Then, it returns {date: symbol('whatever')}
, which I can use to check (although is a bit weird).
Things start to get funny when such value is passed to another mock function, something equally simple:
const parse = {
makeDate: jest.fn(x => x).mockName('makeDate'),
};
The code I’m testing calls this mock function like this:
parse.makeDate(new Date(startDate)) // startDate is a Symbol on my tests
So later I have to do expect(parse.makeDate).toHaveBeenCalledWith({ date: startDate });
.
Is there any other way to have a more simplistic implementation of this?
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (1 by maintainers)
Top GitHub Comments
Hello 👋
In the first case,
new Date()
will give you an empty object becausex => x
is called as a constructor. When something is returned in a constructor, the behaviour in JavaScript is the following:So, when you just use the symbol, you end up in case 1. The symbol is ignored, so a new object is created and returned. It is empty because the constructor your are using is a simple function that does not mutate
this
(and has nothing in itsprototype
property).When you use
{ date: symbol('whatever') }
, the constructor now returns an object, which means that we are in case 2. You get back was is returned; it’s still not aDate
.It depends on what your are trying to achieve, why you are using a symbol in the first place and how you want to make your assertion.
As far as I am concerned my experience with mocking
Date
has been pretty straightforward but the setup to make is pretty involved. I usually use the following code:I have no idea if this is the recommended way of mocking
Date
but I have had success with it.This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.