Home > Back-end >  How to check if array contains defined values using supertest?
How to check if array contains defined values using supertest?

Time:11-15

Let's say in response during tests I have such array:

array = [
 'a',   'b',
 'c',   'd',
 'e',   'f',
 'g',   'h',
 'i',   'j'
]

And I want to check if this array really contains those values:

array.should.be.a.Array()
.with.lengthOf(response.body.length)
.and.have.properties('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');

As you can see I can't use here have.properties because it's array, not object. So, how can I check ?

CodePudding user response:

You can use should.deepEqual to match length and values with order

const arr = [
 'a',   'b',
 'c',   'd',
 'e',   'f',
 'g',   'h',
 'i',   'j'
];

arr.should.deepEqual(arr);
console.log("test passed");
<script src="https://cdnjs.cloudflare.com/ajax/libs/should.js/13.2.3/should.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you need an exact match go with Chandan's answer, if you need to match a subset, you can use should.containDeep (see the docs). Here's an example:

const arr = [
 'a',   'b',
 'c',   'd',
 'e',   'f',
 'g',   'h',
 'i',   'j'
];

arr.should.containDeep(['a', 'b', 'c', 'd']);
console.log("test passed");
<script src="https://cdnjs.cloudflare.com/ajax/libs/should.js/13.2.3/should.min.js"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related