如何在反应中异步调用后测试状态更新和组件重新渲染

run*_*us2 5 javascript unit-testing asynchronous reactjs enzyme

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

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

发现.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
  }
}

Run Code Online (Sandbox Code Playgroud)

Spotify模拟:

const getUserInfoMock = jest.fn();

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

export default mock;
Run Code Online (Sandbox Code Playgroud)

用户.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>
  );
};
Run Code Online (Sandbox Code Playgroud)

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

  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);
  });
Run Code Online (Sandbox Code Playgroud)

另一方面,当我只检查是否调用了模拟时,我不需要使用 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);
  });

Run Code Online (Sandbox Code Playgroud)

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

Seb*_*nes 6

您应该按照Dan Abramov 的博客文章将影响渲染的调用包装在 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);
  });
Run Code Online (Sandbox Code Playgroud)


小智 -1

参考:当模拟点击调用调用 Promise 的函数时,使用 React 的 Jest 和 Enzyme 进行测试

将您的期望语句包装在setImmediate中

setImmediate(() => {
    expect(spotifyMock.getUserInfo).toHaveBeenCalledTimes(1);
})
Run Code Online (Sandbox Code Playgroud)