【问题标题】:Jest TypeError: Cannot read property of nullJest TypeError:无法读取 null 的属性
【发布时间】:2021-08-17 03:45:35
【问题描述】:

我有一个外部应用程序的设置并在 const 中启动它,然后将其放入 const allowAppInstance appConfig 的配置中

export const setupRemote = () => {
  if (isRemoteAvailable) {
    try {
      ...

      const allowAppInstance = SetupConfig.start(remoteInstance);

      return {
        allowAppInstance,
      };
    } catch (e) {
      console.error(e);
    }
  }
};

我在这里导出

export const appSetupConfig = () => setupRemote().allowAppInstance;

在组件中,我得到了这个设置并将它放在一个 const 中

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

      useEffect(() => {
        const allowAppInstance = appSetupConfig();
    
        ...the rest of code
    
      }, []);

应用程序可以工作,但是当我运行测试时,开玩笑并没有让它通过,它会导致这个错误:

  TypeError: Cannot read property 'allowAppInstance' of null

  43 | };
  44 | 
> 45 | export const appSetupConfig = () => setupRemote().allowAppInstance;

有什么方法可以模拟 allowAppInstance 以通过测试吗?我真的不知道该怎么做,我做错了什么

【问题讨论】:

  • 单元测试时isRemoteAvailable的值是多少?我认为虚假可能会导致 window.setup 未被定义,并最终导出以供使用。

标签: javascript reactjs jestjs react-testing-library testing-library


【解决方案1】:

您可以在测试顶部使用模拟功能手动添加设置属性: 但根据您的应用使用 allowAppInstance 的方式,您可能需要做一些额外的工作。

const setup = {appConfig: jest.fn();}
Object.defineProperty(window, 'setup', setup);

【讨论】:

  • 您好,我从窗口中删除了 const 以尝试改进,现在测试指向我另一个错误,您知道如何帮助我吗?
  • 您好,是的,您仍然需要模拟 myApp 模块: import { appSetupConfig } from '../myapp'; jest.mock('../myapp', () => ({ appSetupConfig : jest.fn() }))
猜你喜欢
  • 2020-07-09
  • 2020-01-29
  • 1970-01-01
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多