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

时间:2019-08-29 17:33:28

标签: reactjs jestjs

我们正在使用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不变(此文件中还有其他依赖于它的测试。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

在深入地研究了玩笑的文档和反复试验后,我发现了金块。这是最终的测试用例代码:

// 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

相关问题