【问题标题】:Expect one of two object with deep equal期望具有深度相等的两个对象之一
【发布时间】:2020-09-09 12:05:47
【问题描述】:

对于 Chai 期望,我正在尝试将 API 响应与预期响应进行比较。 API 的预期响应随时间而变化,可能是两种可能的静态 JSON 之一。

在 Chai 中有什么方法可以期待这两个 JSON 之一?

我知道它对单个值非常有效:expect(actualResponse).to.deep.equal(expectedJson);

但我想要类似:expect(actualResponse).to.deep.equal(expectedJson1, expectedJson2);

【问题讨论】:

    标签: mocha.js chai


    【解决方案1】:

    您可以使用chai.satisfy(matcher[, msg]) 方法。

    例如

    import { expect } from 'chai';
    import _ from 'lodash';
    
    describe('63811326', () => {
      it('should pass', () => {
        function genResponse() {
          const successResponse = {
            data: {},
            success: true,
          };
          const failResponse = {
            success: false,
            errorMessage: 'API error',
          };
          return Math.random() > 0.5 ? failResponse : successResponse;
        }
    
        const expectedJson1 = { data: {}, success: true };
        const expectedJson2 = { success: false, errorMessage: 'API error' };
        expect(genResponse()).to.satisfy((actualResponse) => {
          console.log(actualResponse);
          return _.isEqual(actualResponse, expectedJson1) || _.isEqual(actualResponse, expectedJson2);
        });
      });
    });
    

    第一次执行的单元测试结果:

      63811326
    { success: false, errorMessage: 'API error' }
        ✓ should pass
    
    
      1 passing (26ms)
    

    第二次执行的单元测试结果:

      63811326
    { data: {}, success: true }
        ✓ should pass
    
    
      1 passing (31ms)
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2021-10-10
      • 2012-01-24
      • 2011-07-23
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多