简体   繁体   English

检查值是字符串还是mocha / chai test中的数字

[英]check if value is a string or a number in mocha/chai test

I'm curious about how to test a value to be a string or number with chai . 我很好奇如何使用chaivalue测试为string number I know how to write a test for a string or a number , when it's a strict test. 我知道如何为stringnumber编写测试,当它是严格测试时。 But how to deal with it, when value could either be one of them? 但是,当value可能是其中之一时,如何处理呢?

A test for a string: 对字符串的测试:

describe("test", () => {
    it("should be a string", () => {
       let value = "1234";
       value.should.be.a("string");
    });
});

A test for a number: 对数字的测试:

describe("test", () => {
    it("should be a number", () => {
       let value = 1234;
       value.should.be.a("number");
    });
});

Is there a build-in way of chai to do this? 是否有一个内置的方式chai做到这一点?

I know that I could do some workarounds, like below. 我知道我可以做一些解决方法,如下所示。 But that feels kind of hacky . 但这感觉有点hacky

describe("test", () => {
    it("should be a number or string", () => {
       let value = 1234;
       (typeof value).should.be.oneOf(["string", "number"]);
    });
});

You could write your own method: 你可以编写自己的方法:

chai.Assertion.addMethod('stringOrNumber', function () {
    //Check if it is a string or a number here
});

Then in your test: 然后在你的测试中:

expect(myValue).to.be.stringOrNumber();

See plugin utilities documentation 请参阅插件实用程序文档

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

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