Reputation: 11677
any idea how to mock an “import” for testing? I use jest now.
ie:
//browser.js
export const browser = {
id: undefined
};
export const getBrowser = function() {
return browser;
};
//fetch-data.js
//code that uses the browser and I wanna test
import {getBrowser} from './../components/browser';
export const fetchData = function() {
const browser = getBrowser();
return Object.assign({dontcare:1}, browser);
};
//My test... Im using jest
import {fetchData} from './../fetch-data.js';
expect(fetchData()).toBe({......});
};
now in the test file I want to mock the response of the browser
component…
Any ideas?
Thanks!
Upvotes: 0
Views: 500
Reputation: 740
Your function in fetch-data.js
is dependent upon exports from browser.js
.
You would find that browser
and getBrowser
both are undefined depending on your jest configuration.
Since browser.js
is ready for export, you can use jest.requireActual(moduleName)
to import and use that module infetch-data.js
. I would do this in the following way:
jest.mock("./browser", () => {
const br = jest.requireActual("browser");
return {
...br,
browser: {id:'changed value'}
};
})
Upvotes: 0
Reputation: 11677
Got to resolve it in the end with the help of one of the posts but in a different way with Sinnon.js
1) I import the browser component in my test:
import * as browserModule from './../components/browser';
2) now in my tests I'll mock the methods I want:
sinon.stub(browserModule, 'getBrowser').returns({id: 1});
3) all good from here, I call my test object and it gets the proper mocked responses :)
Upvotes: 1
Reputation: 336
you need to find a way to inject the the getBrowser
function into the fetchData
export const fetchData = function(injectedFunction) {
const browser = injectedFunction !== undefined? injectedFunction() || getBrowser();
return Object.assign({dontcare:1}, browser);
};
this way you can now //your test... Im using jest
import {fetchData} from './../fetch-data.js';
import {getBrowser} from './../components/browser';
let mockBrowser = mock(getBrowser);// <choose your mock library>
// mock the behavior then inject it to the fetchData
expect(fetchData(mockBrowser)).toBe({......});
};
that's why it is good to apply dependency injection in your code to be able to test it with ease
for me you can use http://sinonjs.org/ for test spies, stubs and mocks
Upvotes: 0