debitoor / chai-subset

"containSubset" object properties matcher for Chai
http://chaijs.com/plugins/chai-subset/
MIT License
82 stars 20 forks source link

Adding a compare function to be used in expected object template #66

Closed sergejsha closed 6 years ago

sergejsha commented 6 years ago

The idea of this PR is to add a possibility of using a compare function inside the expected object. This allows not only checking for static values, but also adding more sophisticated checks like check for being not null, check for been defined etc.

Here is an example. I store an object and then additionally check that id, createdAt and updatedAt properties are present in the object. The check would not be possible without the compare function because returned values are expected to be different between different test runs.

        it('should store object', async function () {
            const publisherData = {
                name: 'publisher',
                descr: 'description',
                urls: { homepage: 'http://homepage' }
            }
            const publisher = await repository.findOrCreatePublisher(publisherData)
            expect(publisher).containSubset({
                ...publisherData,
                id: id => id,
                createdAt: createdAt => createdAt,
                updatedAt: updatedAt => updatedAt
            })
        })

This might also solve #64.

eagleeye commented 6 years ago

@beworker not bad =) Please add some examples to the README

sergejsha commented 6 years ago

Here we are. Some examples were added.

eagleeye commented 6 years ago

@beworker thanks a lot!

sergejsha commented 6 years ago

Thanks you for releasing! Now I can remove locally modified chai-subset copy :)

elmigranto commented 5 years ago

This breaks comparing functions (see https://github.com/debitoor/chai-subset/issues/68) or throws on class instances.

const int = (left, right) => left - right
class Expected {}

expect({comparator: int, ctor: Expected}).to.containSubset({
  comparator: int, // fails, even though function is the same
  ctor: Expected,  // throws TypeError
})

// TypeError: Class constructor Expected cannot be invoked without 'new'
//      at <redacted>/node_modules/chai-subset/lib/chai-subset.js:75:13
//      at Array.every (<anonymous>)
//      at compare (node_modules/chai-subset/lib/chai-subset.js:68:33)
//      at Proxy.<anonymous> (node_modules/chai-subset/lib/chai-subset.js:21:5)
//      <redacted>

@beworker @eagleeye