我正在尝试测试类似的功能:
function foo() {
return {
key_a: "val_a",
key_b: new Date()
};
如何为这种情况制作预期的测试对象?
const expectedObject = {
key_a: "val_a",
key_b: new Date()
}
expect(foo()).toEqual(expectedObject)?
- Expected
+ Received
- "key_b": 2019-01-23T14:04:03.060Z,
+ "key_b": 2019-01-23T14:04:03.061Z,
最佳答案
对此有多种方法,许多在 this thread 中进行了讨论。 .
在这种情况下,最简单干净的方法可能是监视 Date
并使用 mockFn.mock.instances
获取从 new Date()
返回的内容像这样:
function foo() {
return {
key_a: "val_a",
key_b: new Date()
};
}
test('foo', () => {
const spy = jest.spyOn(global, 'Date'); // spy on Date
const result = foo(); // call foo
const date = spy.mock.instances[0]; // get what 'new Date()' returned
const expectedObject = {
key_a: "val_a",
key_b: date // use the date in the expected object
};
expect(result).toEqual(expectedObject); // SUCCESS
})
关于javascript - 测试 jest 和 new Date(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329398/