gpt4 book ai didi

reactjs - 如何模拟从第三方库导出的类?

转载 作者:行者123 更新时间:2023-12-02 19:53:13 25 4
gpt4 key购买 nike

我们正在使用 Jest 为 React 组件编写一些单元测试,我遇到了一个我似乎无法全神贯注的问题。我们需要从导出多个类的第三方库中模拟单个类。但是我们不想模拟所有类,只模拟一个类。

// third-party-library
export ClassA;
export ClassB;
export ClassC;
// hooks.js
import { useState } from 'react';
import { ClassB } from 'third-party-module';

export const myHook = () => {
const [mystate, setMystate] = useState({});
const classB = new ClassB();
// ...implementation...
return mystate;
};
// our-test-case.js
import { myHook } from '../hooks.js';

// --- This isn't quite what I want (ClassA and ClassC are mocked)
// jest.mock('third-party-library');
// ---

// --- This also does not appear to work (ClassA and ClassC are still mocked)
// jest.mock('third-party-library', () => ({
// __esModule: true,
// ClassB: class {
// ...mock implementation..
// }
// });
// ---

it('mock ClassB', () => {
const mystate = myHook();
// ...implementation...
});

在这个例子中我只想模拟ClassB。我想保持 ClassAClassC 相同(此文件中还有其他依赖于它的测试。我做错了什么?

最佳答案

在深入研究 Jest 文档和反复试验后,我找到了金 block 。这是最终的测试用例代码:

// our-test-case.js
import { myHook } from '../hooks.js';

jest.mock('third-party-library', () => ({
__esModule: true,
...jest.requireActual('third-party-library'), // This is the golden nugget.
ClassB: class {
...mock implementation..
}
});

it('mock ClassB', () => {
const mystate = myHook();
// ...implementation...
});

引用:https://jestjs.io/docs/en/bypassing-module-mocks

关于reactjs - 如何模拟从第三方库导出的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57715281/

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