【问题标题】:How to test state update and component rerender after async call in react如何在异步调用反应后测试状态更新和组件重新渲染
【发布时间】:2020-03-09 16:08:08
【问题描述】:

我正在编写一个简单的应用程序,在单击按钮后,应该执行对 spotify API 的异步调用,并且当 promise 解决时它应该更新组件的状态。我正在使用反应钩子来管理我的组件中的状态。

在我的测试中,我模拟了 API 调用。

spotify.jsx

export default class Spotify {
  constructor(token) {
    this.axiosInstance = axios.create({
      baseURL: baseURL,
      headers: buildHeaders(token),
    });
  }

  async getUserInfo() {
    const userInfo = await this.axiosInstance({
      url: `/me`,
    });
    return userInfo.data
  }
}

spotify 模拟:

const getUserInfoMock = jest.fn();

const mock = jest.fn().mockImplementation(() => ({
  getUserInfo: getUserInfoMock,
}));

export default mock;

用户.jsx

const User = props => {
  const [user, setUser] = useState(null);
  const {token} = useContext(AuthContext);
  const spotify = useMemo(() => new Spotify(token), [token]);

  const getUserInfo = async () => {
    console.log("button clicked")
    const fetched = await spotify.getUserInfo();
    console.log(fetched)
    setUser(fetched);
  }

  return (
    <React.Fragment>
      <p>user page</p>
      <button onClick={getUserInfo} > click me </button>
      {user && (
        <div>
          <p>{user.display_name}</p>
          <p>{user.email}</p>
        </div>
      )}
    </React.Fragment>
  );
};

我的问题是如何正确测试这种行为。我设法让它通过了,但不是在simulate() 上调用await 是一个丑陋的黑客吗?模拟不返回承诺。这是一个测试:

  it('updates display info with data from api', async () => {
    const userInfo = {
      display_name: 'Bob',
      email: 'bob@bob.bob',
    };
    spotifyMock.getUserInfo.mockImplementation(() => Promise.resolve(userInfo));

    wrapper = mount(<User />);
    expect(wrapper.find('p')).toHaveLength(1);
    await wrapper
      .find('button')
      .last()
      .simulate('click');

    wrapper.update();
    expect(wrapper.find('p')).toHaveLength(3);
  });

另一方面,当我只检查是否调用了 mock 时,我不需要使用 async/await 和测试通过:

  it('calls spotify api on click', () => {
    wrapper = mount(<User />);
    expect(spotifyMock.getUserInfo).not.toHaveBeenCalled();
    wrapper
      .find('button')
      .last()
      .simulate('click');
    expect(spotifyMock.getUserInfo).toHaveBeenCalledTimes(1);
  });

我想知道我的测试方式是否正确,如果我想添加一个功能以在组件呈现时从 api 获取数据 - 使用 useEffect 挂钩。 Enzyme 是否完全支持反应钩子? 即使我包装了mountsimulate 函数,我也会遇到警告Warning: An update to User inside a test was not wrapped in act(...)

【问题讨论】:

    标签: javascript reactjs unit-testing asynchronous enzyme


    【解决方案1】:

    您应该按照Dan Abramov's blog post 将影响渲染的调用包装在 async act() 函数中,如下所示:

      it('calls spotify api on click', async () => {
        await act(async () => {
          wrapper = mount(<User />);
        });
        expect(spotifyMock.getUserInfo).not.toHaveBeenCalled();
    
        await act(async () => {
          wrapper
            .find('button')
            .last()
            .simulate('click');
        });
    
        wrapper.update();
        expect(spotifyMock.getUserInfo).toHaveBeenCalledTimes(1);
      });
    

    【讨论】:

      【解决方案2】:

      参考:Testing with React's Jest and Enzyme when simulated clicks call a function that calls a promise

      将您的期望声明包装在setImmediate

      setImmediate(() => {
          expect(spotifyMock.getUserInfo).toHaveBeenCalledTimes(1);
      })
      

      【讨论】:

      • 根据您链接的文档, setImmediate() 是非标准的。
      猜你喜欢
      • 2021-01-27
      • 2020-01-13
      • 2017-03-24
      • 1970-01-01
      • 2023-03-22
      • 2022-07-08
      • 2021-10-15
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多