我们正在使用 Jest 为 React 组件编写一些单元测试,我遇到了一个我似乎无法解决的问题。我们需要从导出多个类的第三方库中模拟单个类。但我们不想模拟所有的类,而只是模拟一个类。
// third-party-library
export ClassA;
export ClassB;
export ClassC;
Run Code Online (Sandbox Code Playgroud)
// 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;
};
Run Code Online (Sandbox Code Playgroud)
// 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...
});
Run Code Online (Sandbox Code Playgroud)
我只想ClassB在这个例子中嘲笑。我想保持ClassA相同ClassC(此文件中还有其他测试依赖于它。我做错了什么?
经过更多挖掘笑话文档和反复试验后,我找到了金块。这是最终的测试用例代码:
// 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...
});
Run Code Online (Sandbox Code Playgroud)
参考: https: //jestjs.io/docs/en/bypassing-module-mocks
| 归档时间: |
|
| 查看次数: |
3793 次 |
| 最近记录: |