测试玩笑和新的Date()

时间:2019-01-23 14:24:30

标签: javascript jestjs

我正在尝试对此进行类似的功能测试:

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,

2 个答案:

答案 0 :(得分:1)

有多种解决方法,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
})

答案 1 :(得分:0)

如果您尝试测试对象“键和属性”:

const expected = { name:'component name' }
const actual = { name: 'component name', type: 'form' }
expect(actual).toMatchObject(expected)