反应组件内的 Jest 模拟异步调用 [英] Jest mock async calls inside react component

查看:23
本文介绍了反应组件内的 Jest 模拟异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 jest/enzyme 的新手,正在尝试模拟对返回 Promise 的 aync 函数的调用,该调用是在 componentDidMount 方法中的 react 组件内部进行的.

I'm new to jest/enzyme and am trying to mock a call to an aync function that returns a Promise, the call is made inside a react component in the componentDidMount method.

该测试试图测试 componentDidMount 设置状态中 Promise 返回的数组.

The test is attempting to test that componentDidMount sets the array returned by the Promise in the state.

我遇到的问题是测试在将数组添加到状态之前完成并通过.我正在尝试使用完成"回调让测试等待承诺解决,但这似乎不起作用.

The issue I'm having is that the test finishes and passes before the array is added to the state. I am trying to use the 'done' callback to have the test wait until the promise resolves but this doesn't seem to work.

我试图在 done() 调用之前将 expect 调用移到该行,但这似乎也不起作用.

I have tried to move the expect calls to the line before the done() call but that doesn't seem to work either.

谁能告诉我我在这里做错了什么?

Can anyone tell me what I am doing wrong here?

正在测试的组件:

componentDidMount() {
  this.props.adminApi.getItems().then((items) => {
    this.setState({ items});
  }).catch((error) => {
    this.handleError(error);
  });
}

我的测试:

    import React from 'react';
    import { mount } from 'enzyme';
    import Create from '../../../src/views/Promotion/Create';

    import AdminApiClient from '../../../src/api/';
    jest.mock('../../../src/api/AdminApiClient');

    describe('view', () => {

      describe('componentDidMount', () => {

        test('should load items into state', (done) => {
          const expectedItems = [{ id: 1 }, { id: 2 }];

          AdminApiClient.getItems.mockImplementation(() => {
            return new Promise((resolve) => {
              resolve(expectedItems);
              done();
            });
          });

          const wrapper = mount(
            <Create adminApi={AdminApiClient} />
          );

          expect(wrapper.state().items).toBe(expectedItems);
        });

      });
    });

推荐答案

您的测试有两个问题.首先,您不能像这样模拟 AdminApiClient.jest.mock 将仅用 undefined 替换模块,因此 getItems.mockImplementation 将不起作用或会抛出错误.也没有必要使用原始的.当你通过 props 将它作为参数传递时,你可以在测试中创建你的模拟.其次,如果您使用承诺,则必须从测试中返回承诺或使用 async/await (文档):

There are two problems with your test. First you cant mock AdminApiClient like this. jest.mock will replace the module with just undefined, so getItems.mockImplementation will have no effect or will throw an error. Also there is no need to use the original one. As you pass it in as an argument via props you can just create your on mock right in the test. Second, if you work with promises you either have to return the promise from your test or use async/await (docs):

it('', async() = > {
  const expectedItems = [{ id: 1 }, { id: 2 }];
  const p = Promise.resolve(expectedItems)
  AdminApiClient = {
    getItems: () = > p
  }
  const wrapper = mount(
    <Create adminApi={AdminApiClient} />
  );
  await p
  expect(wrapper.state().items).toBe(expectedItems);
})

这篇关于反应组件内的 Jest 模拟异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆