【问题标题】:How to write a test that checks for multiple types in chai如何编写一个测试来检查 chai 中的多种类型
【发布时间】:2014-12-17 21:35:25
【问题描述】:

我正在尝试编写一个测试,如果输入是字符串或空值,则该测试将通过

在 chai 里面有没有类似的东西

expect(foo).to.be.a('string').or.a('null')

如果不是,那么在编写需要检查多种类型的测试时,最佳实践是什么?

【问题讨论】:

    标签: unit-testing chai


    【解决方案1】:

    这可能是最简单的方法,因为没有 or 关键字。

    var str = null;
    
    expect(str).to.satisfy(function(s){
        return s === null || typeof s == 'string'
    });
    

    【讨论】:

      【解决方案2】:

      你传递给 chai 的assert 的第一个参数是一个表达式,所以你可以这样做:

      assert(assert.isString(foo) || assert.isNull(foo), 'must be a string or null');

      【讨论】:

      • assert 抛出一个错误,但是这个例子假设它返回一个布尔值。
      【解决方案3】:

      解决方案:

      var str = null;
      expect(str).to.satisfies(output=>!output); // testcase will pass
      
      var str = '';
      expect(str).to.satisfies(output=>!output); // testcase will pass
      
      var str = 'test';
      expect(str).to.satisfies(output=>!output); // testcase will fail
      

      【讨论】:

        【解决方案4】:

        Chai 提供了一个oneOf 方法,它接受一个可能匹配的数组。 OP 的断言,其中类型可以是字符串或空值,因此可以这样编码......

        expect(type(foo)).to.be.oneOf(['string', null])
        

        【讨论】:

        • oneOf 方法是检查值,而不是类型。在这种情况下,它期望 foo 等于 'string' 或 null。
        • 是的,你说得对,阿尼。我已经更正了代码以针对 type(value) 而不是 value 进行断言。
        • type-detect 模块也是必需的。
        • @WillP, typeof null 是 'object' 而不是 null,所以你的决定是不对的
        【解决方案5】:

        我会这样写

        try {
          expect(foo).to.be.a('string');
        } catch (e) {
          expect(foo, 'expected a string or').to.be.a('null');
        }
        

        输出将是

        AssertionError: expected a string or: expected 100 to be a null
        

        【讨论】:

          猜你喜欢
          • 2022-09-23
          • 2016-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多