Spy not working when depdendent service is destructured
See original GitHub issueHi there,
Following the issue noted in #106, I found out why my spy won’t work, despite following the documentation properly:
Scenario:
You’re testing a module and its function called MyModule.getStuff()
, which itself depends on another service that you therefore want to stub, say using expect.spyOn(otherService, 'getData');
.
Issue:
The spy will not be called if MyModule’s getStuff()
is imported using ES6 destructuring,
e.g.:
/* MyModule.js */
// will be caught by the spy:
const otherService = require('./otherService');
// won't be caught by the spy:
const { getData } = require('./otherService');
That’s what stumped me on the issue for a good day. Changing the import back to the oldschool version made my test with the spy work just fine.
Issue Analytics
- State:
- Created 7 years ago
- Comments:5
Top Results From Across the Web
jest.spyOn is not working with destructured functions
When you call jest.spyOn(Funcs, 'foo'); , the Funcs object gets modified to have a new foo property. Your first code example is accessing ......
Read more >How to stub a dependency of a module - Sinon.JS
For the stubbing to work, the stubbed method cannot be destructured, neither in the module under test nor in the test. An example....
Read more >ES6 Class Mocks - Jest
If you use arrow functions in your classes, they will not be part of the mock. The reason for that is that arrow...
Read more >How to @Spy a mocking dependency | Sylhare's blog
So here's the trick to still test your newly created class using the old tests. Because only mocking it is not testing it!...
Read more >Testing services - Angular
To check that your services are working as you intend, you can write tests ... Instead, mock the dependency, use a dummy value,...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@batjko because the mechanism by which all kinds of spies in JS functions is by replacing an object property with a spy function. There’s nothing in JS that allows replacing a direct reference to a value with another one when it’s not in scope (via reassignment)
Maybe this can help: https://stackoverflow.com/questions/60149391/how-to-use-jasmine-js-spy-on-a-required-function