【问题标题】:Jest expect mock to be called with an object not containing a specific field开玩笑期望使用不包含特定字段的对象调用模拟
【发布时间】:2019-08-05 04:39:39
【问题描述】:

我想验证一个模拟 API 是用一个不包含特定字段的对象调用的。

expect(api.method).toBeCalledWith(expectedObject);

由于api.method 调用的实际参数可以是expectedObject 的子集,如果actualObject 包含更多字段(其中可能是特定字段),则此测试也可以通过。

如果actualObject 不等于expectedObject,我该如何重写测试以使测试失败?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    你可以试试这样的

    // get the first call to your method
    const method = api.method.mock.calls[0]; 
    
    //check if you have expectedObject as a subset of the arguments
    expect(method[0]).toMatchObject(expectedObject); 
    
    //key is the field that shouldn't be part of the arguments
    expect(method[0].has(key)).toEqual(false); 
    

    【讨论】:

    • 非常感谢卡里姆!这让我走上了正轨!
    【解决方案2】:
    // since several tests use this mock I have to ensure to have the latest call
    const lastMockApiCall = api.method.mock.calls[api.method.mock.calls.length - 1]; 
    const apiCallParams = lastMockApiCall[0];
    expect(apiCallParams).not.toHaveProperty('specificFieldIdontWant');
    

    【讨论】:

    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 howwhygreatly improved if it included an explanation 这解决了问题。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    【解决方案3】:

    我正在使用以下

    expect(body[0].email).toEqual(undefined);
    

    当返回的 API 数组的第一个对象中没有电子邮件时传递。

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2021-07-03
      • 2021-07-30
      • 2021-12-30
      • 2020-08-20
      • 2018-12-30
      • 2018-10-23
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多