Given a test like this: (there's a lot of code here, but you can definitely get through it—read the comments)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('BookPlayerPageGenerator()', function () { | |
var bppg, dlManager, dlManagerMock; | |
before(function () { | |
// ... (omitted) set up audio and button elements and append them to body ... | |
// Set up a dummy object with a stubbed BookDownloadManager interface | |
dlManager = { downloadBook: function (book_id, chapter_obj) {}, | |
downloadChapter: function (book_obj) {} }; | |
dlManagerMock = sinon.mock(dlManager); // setup a mock of the dlManager object | |
// dlManager, NOT dlManagerMock, passed in args | |
bookPlayerArgs = {/* other args omitted, */ 'bookDownloadManager': dlManager }; | |
bppg = new BookPlayerPageGenerator(bookPlayerArgs); | |
}); | |
describe('#generatePage()', function () { | |
it('adds onclick to the book download DOM element', function () { | |
bppg.generatePage(/* ... args */); // run method | |
dlManagerMock.expects("downloadBook").once().withExactArgs(BOOK_OBJECT); // set up expectations for mock | |
$('#downloadBook').trigger('click'); // should call dlManager's #downloadBook() method matching expectations | |
dlManagerMock.verify(); // verify that #downloadBook() has been called or fail if it hasn't | |
}); | |
}); | |
}); |
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