如何在每个测试中以不同的方式模拟导入依赖关系

编程入门 行业动态 更新时间:2024-10-28 12:25:44
本文介绍了如何在每个测试中以不同的方式模拟导入依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个导入另一个文件.我想在每个测试中以不同的方式模拟其他导入,但要通过导入它的文件来显示它.

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 });

更多推荐

如何在每个测试中以不同的方式模拟导入依赖关系

本文发布于:2023-11-25 17:07:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中以   关系   方式   测试   在每个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!