Sunday, April 26, 2015

4/26/15 - Mocking with Sinon

When I wrote the Testing with Sinon post a couple days ago I meant to talk about how I was able to use mocking.

Given a test like this: (there's a lot of code here, but you can definitely get through it—read the comments)
Sinon's mocking is interesting, because it keeps the behavior of the object being mocked intact while still allowing you to test how the methods have been called. In the case of this test, I don't care about what the BookDownloadManager#downloadBook method is actually doing, so I created a dummy object with stubbed methods (line 8), and used sinon to mock that (line 9).

At first, I was confused about whether to use the original dlManager object or the dlManagerMock I had created with sinon, but I found that the mock you get from sinon.mock() is an object for you as the tester to verify that methods are being called, while the original object passed into .mock() continues to be what you actually use to interact with the objects being tested. Sam pointed out that this was done to preserve the namespace of the original object. For example, what if dlManager had a function called #verify()?

No comments:

Post a Comment