我有一个导入另一个文件。我想在每个测试中以不同的方式模拟其他导入,但要通过导入它的文件来显示它。
我尝试了通过谷歌搜索进行各种模拟和导入的方法,但是都没有用。
考虑文件:
settings.js
export default { mySetting: null };
store.js
import settings from "./settings";
export default {
settings: { ...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
中模拟这些文件以使所有3个测试都通过而无需编辑settings.js
或store.js
?
注意:
这类似于我的previous question,但是导入依赖项和更改值的解决方案在这种情况下不起作用,因为store
在这里未引用settings
对象,而是克隆它是一个初始值。
答案 0 :(得分:3)
在这种情况下,store
是包含嵌套settings
对象的对象。虽然不可能简单地将store
分配给其他内容,但是可以将store.settings
分配给其他内容。也可以将store.settings.mySetting
设置为其他值:
import store from "./store";
it("default settings", () => {
expect(store.settings.mySetting).toBe(null); // SUCCESS
});
it("mocked to true", () => {
store.settings = { mySetting: true }; // set store.settings to something else
expect(store.settings.mySetting).toBe(true); // SUCCESS
});
it("mocked to false", () => {
store.settings.mySetting = false; // set store.settings.mySetting to something else
expect(store.settings.mySetting).toBe(false); // SUCCESS
});
答案 1 :(得分:0)
我不确定我是否理解你的问题。听起来您只想模拟一个简单的对象
“ {settings:{ mySetting: null }}
”。
let store = {settings:{ mySetting: null }}
it("default settings", () => {
store.settings.mySetting = null
expect(store.settings.mySetting).toBe(null);
});
it("mocked to true", () => {
store.settings.mySetting = true
expect(store.settings.mySetting).toBe(true);
});
it("mocked to false", () => {
store.settings.mySetting = false
expect(store.settings.mySetting).toBe(false);
});