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
1 Answer
Reset to default 4You 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