Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai expect to be one of array elements

Is there any way to assert that string is one of array elements with chai bdd? I couldn't find that in Chai API

expect("bar").to.be.one.of(["bar", "key"]);
like image 795
message Avatar asked Sep 18 '15 22:09

message


People also ask

Should you expect chai?

Differences between expect and should First of all, notice that the expect require is just a reference to the expect function, whereas with the should require, the function is being executed. var chai = require('chai') const expect = chai. expect const should = chai.

How do you compare two objects in Chai?

You can use deep-equal-in-any-order plugin. Chai plugin to match objects and arrays deep equality with arrays (including nested ones) being in any order. It works in a similar way as deep. equal but it doesn't check the order of the arrays (at any level of nested objects and arrays).

What is chai assertion?

Chai assertion library is an external javascript library used to write assertions. Compared to what we write directly in javascript, this assertion library needs less time & effort and easy use. Chai assertion library is available by default in the Postman.

What is deep equal chai?

When you use deepEqual , Chai will go down the object hierarchy and compare every value of every property. Example: const a = {"a": "a"}; const b = {"a": "a"}; expect(a). to. equal(b); // false, as a refers to a different object than b expect(a).


2 Answers

Flip the check around:

expect(["bar", "key"]).to.include("bar");
like image 101
Adrian Lynch Avatar answered Oct 16 '22 14:10

Adrian Lynch


Updated for 2021

The answer below prints out a better error message

expect(res.status).to.be.oneOf([400, 401]);

The error message clearly defines what the expected value is and the returned value.

E.g.

expect(200).to.be.oneOf([400, 401]);

Returns

AssertionError: expected 200 to be one of [ 400, 401 ]

like image 34
PathToLife Avatar answered Oct 16 '22 15:10

PathToLife