小编典典

模拟点击时使用React的Jest和Enzyme进行测试会调用一个调用promise的函数

reactjs

  • React v15.1.0
  • Jest v12.1.1
  • Enzyme v2.3.0

我试图弄清楚如何测试通过单击调用的函数中调用promise的组件。我期望Jest的runAllTicks()功能可以在这里为我提供帮助,但似乎并没有执行承诺。

零件:

import React from 'react';
import Promise from 'bluebird';

function doSomethingWithAPromise() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 50);
  });
}

export default class AsyncTest extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      promiseText: '',
      timeoutText: ''
    };

    this.setTextWithPromise = this.setTextWithPromise.bind(this);
    this.setTextWithTimeout = this.setTextWithTimeout.bind(this);
  }

  setTextWithPromise() {
    return doSomethingWithAPromise()
      .then(() => {
        this.setState({ promiseText: 'there is text!' });
      });
  }

  setTextWithTimeout() {
    setTimeout(() => {
      this.setState({ timeoutText: 'there is text!' });
    }, 50);
  }

  render() {
    return (
      <div>
        <div id="promiseText">{this.state.promiseText}</div>
        <button id="promiseBtn" onClick={this.setTextWithPromise}>Promise</button>
        <div id="timeoutText">{this.state.timeoutText}</div>
        <button id="timeoutBtn" onClick={this.setTextWithTimeout}>Timeout</button>
      </div>
    );
  }
}

和测试:

import AsyncTest from '../async';
import { shallow } from 'enzyme';
import React from 'react';

jest.unmock('../async');

describe('async-test.js', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<AsyncTest />);
  });

  // FAIL
  it('displays the promise text after click of the button', () => {
    wrapper.find('#promiseBtn').simulate('click');

    jest.runAllTicks();
    jest.runAllTimers();

    wrapper.update();

    expect(wrapper.find('#promiseText').text()).toEqual('there is text!');
  });

  // PASS
  it('displays the timeout text after click of the button', () => {
    wrapper.find('#timeoutBtn').simulate('click');

    jest.runAllTimers();

    wrapper.update();

    expect(wrapper.find('#timeoutText').text()).toEqual('there is text!');
  });
});

阅读 492

收藏
2020-07-22

共1个答案

小编典典

在结束测试之前,不需要太多等待等待的承诺。从您可以看到的代码中,有两种主要的实现方法。

  1. 独立测试onClick和您的诺言方法。因此,请检查是否onClick调用了正确的函数,但监视setTextWithPromise,触发单击并断言setTextWithPromise已调用该函数。然后,您还可以获取组件实例并调用该方法,该方法返回承诺,您可以附加处理程序并断言它做了正确的事情。

  2. 公开一个您可以传入的回调道具,当承诺解决时会调用该道具。

2020-07-22