gpt4 book ai didi

javascript - 如何模拟在测试模块中导入的变量,它不是函数参数(使用 describe.each 并在每个测试更改模拟值时执行此操作)

转载 作者:行者123 更新时间:2023-11-30 14:11:31 25 4
gpt4 key购买 nike

我需要在我的 ts-module 中测试功能。

module-to-test.ts

import { config } from './app-config';

export const isSomethingWhatINeedSelector = createSelector(
firstDependencySelector,
secondDependencySelector,
(first, second) => config.key && (first || !second)
);

但我不想为这个案例写很多测试,我想尝试使用describe.each([[],[],[]]) 减少代码行数的功能。

而且我需要在 describe.each 的每次迭代中更改 config.key。当我在测试文件的开头做这样的事情时:

jest.mock('./app-config', () => ({
config: {
key : false,
},
}));

它适用于整个文件和所有测试。我想在“test/it”函数中进行模拟以动态更改键的值。

现在我有了那个代码,但没有按预期工作

describe.each([
[
'should be ....',
true, false
],
[
'should be ....',
false, true
],
/* and etc. ... [], [], [] ... only for questnion here is two params*/
])('Functionality of ...', (
testTitle = '',
mockStatusOfConfigKey,
expected,
) => {
const state = ... /* initial */

beforeEach(() => {
jest.resetModules();
/*....configuring the state*/
});

it(testTitle, () => {
jest.mock('./app-config', () => ({ /*...or doMock(), that don't works*/
config: {
key : mockStatusOfConfigKey,
},
}));
expect(isSomethingWhatINeedSelector(state)).toBe(expected);
});
});

有什么想法可以让模拟在测试函数中动态变化吗?config.key 只是 true/false

最佳答案

来自 Exploring ES6 的两个重要概念(也适用于 TypeScript Modules ):

In ES6, imports are live read-only views on exported values

while you can’t change the values of imports, you can change the objects that they are referring to.


app-config 导出 config 它是一个对象

config 不能赋值给其他东西,但是它指向的对象可以改变

任何导入 config 的代码都会获得对象的实时 View ,并将自动看到对对象的任何修改:

import { config } from './app-config';

...

it(testTitle, () => {
config.key = mockStatusOfConfigKey; // modify the config object
expect(isSomethingWhatINeedSelector(state)).toBe(expected); // SUCCESS
});
});

关于javascript - 如何模拟在测试模块中导入的变量,它不是函数参数(使用 describe.each 并在每个测试更改模拟值时执行此操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54360027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com