最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check if value is a string or a number in mochachai test - Stack Overflow

programmeradmin3浏览0评论

I'm curious about how to test a value to be a string or number with chai. I know how to write a test for a string or a number, when it's a strict test. But how to deal with it, when value could either be one of them?

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?

I know that I could do some workarounds, like below. But that feels kind of hacky.

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

I'm curious about how to test a value to be a string or number with chai. I know how to write a test for a string or a number, when it's a strict test. But how to deal with it, when value could either be one of them?

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?

I know that I could do some workarounds, like below. But that feels kind of hacky.

describe("test", () => {
    it("should be a number or string", () => {
       let value = 1234;
       (typeof value).should.be.oneOf(["string", "number"]);
    });
});
Share Improve this question asked Mar 21, 2017 at 13:43 eisbehreisbehr 12.5k7 gold badges41 silver badges65 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论