简体   繁体   English

玩笑函数 toHaveBeenCalledWith 忽略对象顺序

[英]Jest function toHaveBeenCalledWith to ignore object order

Im testing with what arguments a function was called but its not passing because the order of properties inside an object, like:我用什么参数测试了一个函数被调用但它没有通过,因为对象内部的属性顺序,比如:

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

expect(function).toHaveBeenCalledWith(obj)

The error says that was called like this: { name: 'bla', infos: {info2: '2', info1: '1'} }错误说是这样调用的:{ name: 'bla', infos: {info2: '2', info1: '1'} }

I changed orders but didn't work.我更改了订单但没有用。

You could follow a similar approach to this SO answer .您可以对这个 SO answer遵循类似的方法。

Example:例子:

// 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.toMatchObject() 文档

Expect.toEqual() Docs Expect.toEqual() 文档

  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});
  });

passes for me with Jest 24.9.0用 Jest 24.9.0 传给我

Under the hood , Jest applies "isEqual" check, not referential check引擎盖下,Jest 应用“isEqual”检查,而不是引用检查

But we cannot check for functions equality this way.但是我们不能这种方式检查函数是否相等 Also partial matching will need custom matcher.部分匹配也需要自定义匹配器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM