笑话函数toHaveBeenCalledWith忽略对象顺序

时间:2020-03-24 11:49:48

标签: javascript jestjs

Im测试使用什么参数调用了一个函数,但该函数未通过,因为对象内部属性的顺序如下:

const obj = {
  name: 'Bla',
  infos: {
    info1: '1',
    info2: '2'
  }
}

expect(function).toHaveBeenCalledWith(obj)

该错误表明该调用是这样的:{name:'bla',infos:{info2:'2',info1:'1'}}

我更改了订单,但是没有用。

2 个答案:

答案 0 :(得分:1)

  it('does not care on properties ordering', () => {
    const a = jest.fn();
    a({ a: 1, b: 2, c: {d1: 1, d2: 2} });
    expect(a).toHaveBeenCalledWith({c: {d2: 2, d1: 1}, b: 2, a: 1});
  });

Jest 24.9.0为我通过

the hood下,Jest应用了“ isEqual”检查,而不是引用检查

但是我们不能以这种方式检查for functions equality。另外,部分匹配将需要自定义匹配器。

答案 1 :(得分:0)

您可以对this SO answer采用类似的方法。

示例:

// Assuming some mock setup like this...
const mockFuncton = jest.fn();

const expectedObj = {
  name: 'Bla',
  infos: {
    info1: '1',
    info2: '2'
  }
}

// Perform operation(s) being tested...

// Expect the function to have been called at least once
expect(mockFuncton).toHaveBeenCalled();

// Get the 1st argument from the mock function call
const functionArg = mockFuncton.mock.calls[0][0];

// Expect that argument matches the expected object
expect(functionArg).toMatchObject(expectedObj);

// Comparison using toEqual() instead which might be a better approach for your usecase
expect(functionArg).toEqual(expectedObj);

Expect.toMatchObject() Docs

Expect.toEqual() Docs