I am following a node, express tutorial. Here is a patch route
app.patch('/todos/:id', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['text', 'completed']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
if (_.isBoolean(body.completed) && body.completed) {
body.completedAt = new Date().getTime();
} else {
body.completed = false;
body.completedAt = null;
}
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch((e) => {
res.status(400).send();
})
});
And here is the test suite for the same route:
it('should update the todo', (done) => {
var hexId = dummy[0]._id.toHexString();
var text = 'This should be the new text';
request(app)
.patch(`/todos/${hexId}`)
.send({
completed: true,
text
})
.expect(200)
.expect((res) => {
expect(res.body.todo.text).toBe(text);
expect(res.body.todo.completed).toBe(true);
expect(res.body.todo.completedAt).toBeA('number');
})
.end(done);
});
Test result:
Error: Expected '2017-07-12T18:38:11.814Z' to be a 'number'
The last test case fails because it is recieving a UTC date from the server
instead of good old unix timestamp. But shouldn't it be a timestamp as it is the result of new Date().getTime()?.
I tried logging both body.completedAt() and todo.completedAt() from the route.
body.completedAt() is returning a unix timestamp,
whereas todo.completedAt() is returning the UTC time. So it seems that mongoose is altering the timestamp. But how do I prevent that so that the last test case passes.
I am using the expect assertion library
Well, I was stupid enough not to check my mongodb schema: The test case was failing because the type of completedAt was set to Date
completedAt: {
type: Date,
default: null
}
It should be:
completedAt: {
type: Number,
default: null
}