# sinon-mongo
A Node library that simplifies writing unit tests using sinon for mocking code using the MongoDB client.
You can install it from npm
npm install sinon-mongo
Let's see the most basic example. Imagine you have a function that depends on db
, an instance of the MongoDB client:
findCustomersInOrganization(orgName){
return db
.collection('customers')
.find({ orgName })
.toArray();
}
You can create a sinon stub for the db
object as in:
mockCustomerCollection = sinon.mongo.collection();
mockDb = sinon.mongo.db({
customers: mockCustomerCollection
});
And test the method as in:
it('returns all the customers for the given org name', () => {
const mockCustomers = [{a: 'mock customer'}, {another: 'mock customer'}];
mockCustomerCollection.find
.withArgs({ orgName: 'mockOrgName' })
.returns(sinon.mongo.documentArray(mockCustomers));
return repository.findCustomersInOrganization('mockOrgName').then(customers => {
expect(customers).to.be.eql(mockCustomers);
});
});
See the documentation for the full API and additional examples.
Check it on GitHub: