gpt4 book ai didi

javascript - Jest : Change output of manual mock for different tests within a test suite

转载 作者:数据小太阳 更新时间:2023-10-29 04:20:12 25 4
gpt4 key购买 nike

假设我有以下两个文件:

// index.js
...
import { IS_IOS } from 'common/constants/platform';
...
export const myFunction = () => (IS_IOS ? 'foo' : 'bar');


// index.test.js
...
import { myFunction } from './index';

jest.mock('common/constants/platform', () => ({ IS_IOS: true }));

describe('My test', () => {
it('tests behavior on IOS', () => {
expect(myFunction()).toBe('foo');
});

// --> Here I want to change the value of IS_IOS to false

it('tests behavior if NOT IOS', () => {
expect(myFunction()).toBe('bar');
});
});

如您所见,我的模拟函数返回 IS_IOS: true。我希望它在我的第一次测试后返回 IS_IOS: false。我该怎么做?


我还尝试了 the solution here 的改编版但我无法让它工作,因为模拟返回一个函数:

module.exports = {
foo: jest.genMockFunction();
}

而我的模拟应该返回一个 bool 值,它不会在我正在测试的文件中调用。这就是我在这里所做的:

// common/constants/__mock__/platform
export const setIsIos = jest.fn(val => (IS_IOS = val));
export let IS_IOS;

// index.test.js
...
import { IS_IOS, setIsIos } from 'common/constants/platform';
jest.mock('common/constants/platform');

describe('My test', () => {
setIsIos('foo');

it('tests behavior on IOS', () => {
expect(myFunction()).toBe('foo');
});

setIsIos('bar');

it('tests behavior if NOT IOS', () => {
expect(myFunction()).toBe('bar');
});
});

奇怪的是,当控制台记录时,即 console.log(IS_IOS); 我得到了预期的值。然而,测试似乎使用了原始值,即 undefined

最佳答案

jest.resetModules() 添加到 describe() 测试套件的 beforeEach() 调用中:

describe('EventManager', () => {

beforeEach(() => {
jest.resetModules();
});
...

此外,我还找到了一个关于如何使用 jest 模拟模块的更完整示例 here

关于javascript - Jest : Change output of manual mock for different tests within a test suite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44309510/

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