gpt4 book ai didi

javascript - 仅模拟模块中的一项功能,但保留原始功能

转载 作者:行者123 更新时间:2023-12-01 15:53:58 24 4
gpt4 key购买 nike

我只想从一个模块中模拟一个函数(名为导出),但保持其余模块函数不变。

使用 jest.mock('package-name')使所有导出的函数模拟,这是我不想要的。

我尝试将命名的导出传播回模拟对象......

import * as utils from './utilities.js';

jest.mock(utils, () => ({
...utils
speak: jest.fn(),
}));


但收到此错误:

The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

最佳答案

这个答案的亮点是 jest.requireActual() ,这是一个非常有用的实用程序,它开 Jest 说“嘿,保留所有原始功能并导入它们”。

jest.mock('./utilities.js', () => ({
...jest.requireActual('./utilities.js'),
speak: jest.fn(),
}));
让我们看另一个常见的场景,你正在使用 enzyme ShallowWrapper 并且它与 useContext() Hook 并不顺利,那么你会怎么做?虽然我确定有多种方法,但这是我喜欢的一种:
import React from "react";

jest.mock("react", () => ({
...jest.requireActual("react"), // import and retain the original functionalities
useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))
这样做的好处是你仍然可以使用 import React, { useContext } from "react"在您的原始代码中,而不必担心将它们转换为 React.useContext() 就像你使用 一样jest.spyOn(React, 'useContext')

关于javascript - 仅模拟模块中的一项功能,但保留原始功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59312671/

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