【问题标题】:How to do callback in our component using react jest test cases如何使用 react jest 测试用例在我们的组件中进行回调
【发布时间】:2021-08-02 00:38:18
【问题描述】:

我们如何使用 jest 对以下代码行的成功和失败情况进行回调以进行测试覆盖

const handleService = () => { 
 window.domain.service("1321",'',onSuccess, onFailure)
}

const onSuccess = () => {
....update state values
}
const onFailure = () => {
....update state values
}

【问题讨论】:

    标签: jestjs react-hooks


    【解决方案1】:

    类似这样的:

    • 监视window.domain.service 以访问它收到的呼叫。这将允许您访问那些调用的参数,这些参数将是"1321",'',onSuccess, onFailure
    • 将要测试的函数分配给变量
    • 调用函数以执行其中的代码(这将为您提供覆盖范围)
    • (可选)断言回调函数行为正确

    这里有一个sn-p来帮助演示

    it('should run', () => {
      // Some setup to create the function on the window, may not be needed if done elsewhere.
      // Could be good to do this in a beforeEach and clean up in afterEach to avoid contaminating the window object
      window.domain = {
        service: () => {},
      }
    
      // Spy on the window.domain.service method.
      // Provide a mock implementation if you don't want the real one to be called
      const serviceSpy = jest.spyOn(window.domain, 'service');
    
      executeYourCode();
    
      // capture the arguments to the call
      const [_arg1, _arg2, onSuccess, onFailure] = serviceSpy.mock.calls[0];
    
      // execute the callbacks
      onSuccess();
      onFailure();
    
    });
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2019-09-03
      • 2019-04-21
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多