我有一个导入另一个文件.我想在每个测试中以不同的方式模拟其他导入,但要通过导入它的文件来显示它.
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.
考虑文件:
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); });我如何在settingsDemo.js中模拟settings.js以使所有3个测试都通过?
how do I mock settings.js within settingsDemo.js to have all 3 tests pass?
推荐答案来自探索ES6" :
在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."
换句话说,不可能将settings分配给其他对象,但是可以更改settings的属性,并且无论导入到哪里,这些更改都会自动看到.
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 });更多推荐
如何在每个测试中以不同的方式模拟导入依赖关系
发布评论