I am trying to implement a test (1) for this module (2).
My purpose is to check if the collection is fetched when a particular event is triggered.
As you can see from my comment in (2) I get the message Error: Expected a spy, but got Function.
The module works but the test fails. any ideas?
(1)
// jasmine test module describe('When onGivePoints is fired', function () { beforeEach(function () { spyOn(this.view.collection, 'restartPolling').andCallThrough(); app.vent.trigger('onGivePoints'); }); it('the board collection should be fetched', function () { expect(this.view.collection.restartPolling).toHaveBeenCalled(); // Error: Expected a spy, but got Function. }); });
(2)
// model view module return Marionette.CompositeView.extend({ initialize: function () { this.collection = new UserBoardCollection(); this.collection.startPolling(); app.vent.on('onGivePoints', this.collection.restartPolling); }, // other code });
here is my code. Sorry, something went wrong. You'll see the error message that "Expected a spy, but got Function" when you use one of the matchers that expects to be used with a spy (like toHaveBeenCalled () ), but the object you pass in isn't actually a spy.
Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service’s methods to get a value. This helps keep our unit tests focused on testing the internals of the component itself instead of its dependencies.
Hence, the spy is not there anymore. try something like: However, you could just spy on prototype. Something like that: And then, your test should work. Thanks for contributing an answer to Stack Overflow!
Developer and author at DigitalOcean. Jasmine spies are used to track or stub functions or methods. Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service’s methods to get a value.
You need to get into the actual method, which in this case is on the prototype.
describe('When onGivePoints is fired', function () { beforeEach(function () { spyOn(UsersBoardCollection.prototype, 'restartPolling').andCallThrough(); app.vent.trigger('onGivePoints'); }); it('the board collection should be fetched', function () { expect(UsersBoardCollection.prototype.restartPolling).toHaveBeenCalled(); }); });
Spying on the prototype is a nice trick you can use when you can't get to the actual instance you want to spy on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With