如何在每个测试中以不同的方式模拟导入依赖关系 [英] How to mock an imports dependency differently in each test

查看:119
本文介绍了如何在每个测试中以不同的方式模拟导入依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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中,导入是有关导出值的实时只读视图."

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

这篇关于如何在每个测试中以不同的方式模拟导入依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆