【问题标题】:Test React function components promises behaviour with Jest,测试 React 功能组件承诺使用 Jest 的行为,
【发布时间】:2021-09-02 14:31:46
【问题描述】:

我有一个 React 函数组件。 我将一个函数作为道具传递给组件,它返回一个承诺。 我在onClick 事件上使用该函数,一旦承诺得到解决,我就会更改组件的状态。 比如:

import React, { useState } from 'react';

function myComponent({ aPromiseReturningFunction }) {
    const [myState, setState] = useState('12');
    const clickHandler = () => {
      aPromiseReturningFunction().then(() => { setState('123') })
    };

    return <div onClick={ clickHandler }>{myState}</div>
}

在我的测试中:

const myFunc = jest.fn(() => Promise.resolve(true));
const componentWrapper = shallow(<myComponent aPromiseReturningFunction={ myFunc }/>);
componentWrapper.simulate('click');
expect(componentWrapper.text()).toEqual('123');

显然以上失败了,但我还没有找到任何可以解释如何正确测试上述内容的东西。当然,如果我在 Promise 之外更改状态,则测试通过。

有什么建议吗?

【问题讨论】:

    标签: reactjs jestjs asynctest


    【解决方案1】:

    由于click 正在异步更新承诺后的状态,我会使用act

    import { act } from 'react-dom/test-utils'; // other testing libraries have similar methods that test async events
    
    const myFunc = jest.fn(() => Promise.resolve(true));
    
    it('updates text after onclick', () => {
      const componentWrapper = shallow(<myComponent aPromiseReturningFunction={ myFunc }/>);
      act(() => {
        componentWrapper.simulate('click');
      });
    
      expect(componentWrapper.text()).toEqual('123');
    });
    

    【讨论】:

      【解决方案2】:

      感谢alextrastero,我终于找到了解决办法。

      alextrastero 的回答中缺少的是我们应该将 act() 包含在 async/await 中,例如:

      import { act } from 'react-dom/test-utils'; // other testing libraries have similar methods that test async events
      
      const myFunc = jest.fn(() => Promise.resolve(true));
      
      it('updates text after onclick', async () => {
        const componentWrapper = shallow(<myComponent aPromiseReturningFunction={ myFunc }/>);
        await act(() => {
          componentWrapper.simulate('click');
        });
      
        expect(componentWrapper.text()).toEqual('123');
      });
      

      为了让它工作,我还需要使用regenerator-runtime/runtime 包。

      【讨论】:

        猜你喜欢
        • 2019-07-09
        • 2021-08-30
        • 1970-01-01
        • 2016-07-23
        • 2020-09-21
        • 2020-09-14
        • 2020-11-02
        • 2020-04-08
        • 1970-01-01
        相关资源
        最近更新 更多