Reputation: 9571
I have a config file that is imported into the file I will be testing, and I need the ability to mock out the config file, but I seem to be doing something wrong - I have
app.js
import config from './config';
export default class App{
static get(){
//refers to config
}
}
test file
import App from './app';
it('should do something', () => {
jest.mock('./config', () => {
return {
//mocked config
}
})
})
but when running the test, I am getting the real config and not the mocked one. Any ideas?
Upvotes: 6
Views: 5229
Reputation: 110922
Just move the mock line after the inputs.
import App from './app';
jest.mock('./config', () => {
return {
//mocked config
}
})
it('should do something', () => {
})
The problem is that you import App
first and later on you mock config
, but how mocking works in Jest is like it replaces the mocked module with your mock so if you import something before mocking its dependencies will end up in an import of the original not the mocked version.
You may wonder why it works in my example even the mock is not declared before the import. Its cause Jest will hoist all mock
calls on top of its scope block at compile time.
Upvotes: 10