I have a file that imports another. I want to mock the other import differently in each test yet have it show through the file that imports it.
I have tried various mocking and importing approaches through googling but none have worked.
Consider the files:
settings.js
export default { mySetting: null };
store.js
import settings from "./settings";
export default {
settings,
};
settingsDemo.js
import store from "./store";
it("default settings", () => {
expect(store.settings.mySetting).toBe(null);
});
it("mocked to true", () => {
expect(store.settings.mySetting).toBe(true);
});
it("mocked to false", () => {
expect(store.settings.mySetting).toBe(false);
});
how do I mock settings.js
within settingsDemo.js
to have all 3 tests pass?
From "Exploring ES6"
:
"In ES6, imports are live read-only views on exported values."
"Note that while you can’t change the values of imports, you can change the objects that they are referring to."
In other words, it is not possible to assign settings
to a different object, but it is possible to change properties on settings
and those changes will automatically be seen wherever it is imported.
With that in mind, here is a working test:
import store from "./store";
import settings from './settings'; // import settings
it("default settings", () => {
expect(store.settings.mySetting).toBe(null); // SUCCESS
});
it("mocked to true", () => {
settings.mySetting = true; // change the mySetting property
expect(store.settings.mySetting).toBe(true); // SUCCESS
});
it("mocked to false", () => {
settings.mySetting = false; // change the mySetting property
expect(store.settings.mySetting).toBe(false); // SUCCESS
});