gpt4 book ai didi

reactjs - Jest jest.mock函数具有不同的返回值

转载 作者:行者123 更新时间:2023-12-02 03:27:49 25 4
gpt4 key购买 nike

用 Jest 和 enzyme 测试 react 和 typescript ,我如何模拟这个 ExpectsVideo 函数,以便我可以根据我的测试用例场景定义它是否返回 true 或 false

jest.mock('utils/media-utils', () => ({
expectsVideo: () => true,
myOtherFunctions: jest.fn()
}));

utils/media-utils(如果是我正在测试的 react 组件中导入的文件)。如果我尝试从外部引用对象,则会出现错误,指出不能使用超出范围的变量。尝试了各种实现,我遇到了不同的博客,但没有帮助。

最佳答案

mockImplementation 应该有帮助,而 mocking whole module :

import * as mediaUtils from 'utils/media-utils';

mock('utils/media-utils'); // automocking whole module

it('....1...', () => {
mediaUtils.expectsVideo.mockImplementation(() => true);
});

it('....2...', () => {
mediaUtils.expectsVideo.mockImplementation(() => false);
});

顺便说一句,对于从外部引用返回错误的变量(来自 jest.doMock documentation 部分):

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

这就是为什么在模拟模块时所有 constlet 甚至都没有定义。

关于reactjs - Jest jest.mock函数具有不同的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710766/

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