Jest函数toHaveBeenCalledWith忽略对象顺序

问题描述 投票:0回答:2

我用一个函数调用了什么参数进行测试,但是由于对象内部属性的顺序而没有通过,例如:

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

expect(function).toHaveBeenCalledWith(obj)

错误说这是这样的:{name:'bla',infos:{info2:'2',info1:'1'}}

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

javascript jestjs
2个回答
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


0
投票
  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下,笑话将应用“ isEqual”检查,而不是引用检查

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

© www.soinside.com 2019 - 2024. All rights reserved.