Mocking external dependencies

Okay, you can write some integration tests. Is it enough? Not yet. Let's think. We really need to connect to external services? What if they're down? Of course, our test will fail but not for some application error. To avoid this, we will use Mocks.

Mocking is the technique used to simulate some object/service/component and return a predefined response when its called. We'll not connect with real services, so we'll be using sinon.mock to create a mock model for our Teams schema, and we'll test the expected result:

// Test will pass if we get all teams
        it("should return football teams",(done) => {
            var TeamMock = sinon.mock(Team);
            var expectedResult = {status: true, team: []};
            TeamMock.expects('find').yields(null, expectedResult);
            Team.find(function (err, result) {
                TeamMock.verify(); //Verifies the team and throws an exception if it's not met 
                TeamMock.restore(); //Restore the fake created to his initial state
                expect(result.status).to.be.true;
                done();
            });
        });

All okay at this point. Now, let's evaluate another very important aspect of testing, code coverage.

Make sure that sinon is downloaded in your project and imported in your current test file to make the example work, same as any external model you may need. You can find more info about sinon at http://sinonjs.org.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset