在React组件中开玩笑的模拟异步调用 [英] Jest mock async calls inside react component

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

问题描述

我是开玩笑/酶的新手,正在尝试模拟对返回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()调用之前的那一行,但这似乎也不起作用.

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将无效或抛出错误.另外,也无需使用原始版本.当您通过道具将其作为参数传递时,您可以在测试中直接创建on模拟.其次,如果您使用诺言,则必须从测试中返回诺言或使用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);
})

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

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