Supasate Supasate - 1 month ago 20
JSON Question

chai - expect an array contains a JSON with a pair of desired key and value

I would like to use chai to 'expect' that an array contains a JSON object with a pair of desired key and value or not.

For example, my array looks like this:

[{ path: '/products/setImage', message: 'hello', ... }, {...}]


I would like to check that this array contains a pair of path: '/products/setImage' in any JSON element in this array or not.

Answer

I was able to achieve this by using the chai-subset plugin:

const chai = require('chai')
const expect = chai.expect
const chaiSubset = require('chai-subset')
chai.use(chaiSubset)

let x = [
    { path: '/products/setImage', message: 'hello', foo: 'bar' },
    { foo: 'baz'}
]

expect(x).to.containSubset([{path: '/products/setImage'}])
expect(x).not.to.containSubset([{path: '/products/setImages'}])
Comments