仅模拟模块中的一个功能,但保留原始功能 [英] Mock only one function from module but leave rest with original functionality

查看:24
本文介绍了仅模拟模块中的一个功能,但保留原始功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想模拟一个模块中的单个函数(命名为导出),但保持模块的其余功能完好无损.

I only want to mock a single function (named export) from a module but leave the rest of the module functions intact.

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

Using jest.mock('package-name') makes all exported functions mocks, which I don't want.

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

I tried spreading the named exports back into the mock object...

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

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

但得到这个错误:

jest.mock() 的模块工厂不允许引用任何范围外的变量.

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

推荐答案

这个答案的亮点是 jest.requireActual(),这是一个非常有用的实用程序,它可以用来开玩笑说嘿保持所有原始功能完整并导入".

The highlight of this answer is jest.requireActual(), this is a very useful utility that says to jest that "Hey keep every original functionalities intact and import them".

jest.mock('./utilities.js', () => ({
  ...jest.requireActual('./utilities.js'),
  speak: jest.fn(),
}));

让我们来看另一个常见的场景,你正在使用酶 ShallowWrapper 并且它不适合 useContext() 钩子,那么你打算怎么做?虽然我确定有多种方法,但这是我喜欢的一种:

Let's take another common scenario, you're using enzyme ShallowWrapper and it doesn't goes well with useContext() hook, so what're you gonna do? While i'm sure there are multiple ways, but this is the one I like:

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')

The perk of doing it this way is that you can still use import React, { useContext } from "react" in your original code without worrying about converting them into React.useContext() as you would if you're using jest.spyOn(React, 'useContext')

这篇关于仅模拟模块中的一个功能,但保留原始功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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