开玩笑错误 -- 无法读取未定义的 属性 'get'

Jest error -- Cannot read property 'get' of undefined

我在 React 的一个组件内配置了一个服务,我在玩笑和测试库时遇到问题,应用程序正在运行,但测试被阻止。

  import { appSetupConfig } from '.../myapp'
  import theConfig from '.../config'

  useEffect(() => {
    const allowAppInstance = appSetupConfig();

    allowAppInstance.get(theConfig).then((value) => {
       if (value.something) {
           Do Something;
       } 
    ...the rest of code

  }, []);

这个theConfig 是一个包含对象的外部文件。 这是错误:

  TypeError: Cannot read property 'get' of undefined

  37 |     const allowAppInstance = appSetupConfig();
  38 | 
> 39 |     allowAppInstance.get(theConfig).then((value) => {

有什么办法可以模拟这个 get in jest 的 setup.js? 我不一定需要测试这个项目,但没有它我无法继续。

是的,有。所以看起来你在某个时候调用了 jest.mock('.../myapp') 或类似的。在 Jest 为模块创建的模拟对象中,每个模拟函数 returns undefined。您需要在 appSetupConfig 上模拟一个 return 值,它本身就是一个模拟对象,具有您需要的方法,例如 get。然后 get 又需要 return 一个模拟承诺,依此类推。在您的安装文件中,这看起来像:

import { appSetupConfig } from '.../myapp'
...
jest.mock('.../myapp');
appSetupConfig.mockReturnValue({
  get: jest.fn().mockResolvedValue({ something: jest.fn() }),
});

你的 .then 块将在 value 设置为 undefined 的测试中调用,但你可以模拟不同的解析值或拒绝承诺用于特定测试。