【问题标题】:What is the best way for testing asynchronous react component测试异步反应组件的最佳方法是什么
【发布时间】:2016-04-12 12:23:30
【问题描述】:

我想用 mocha 测试登录组件的反应

const loginView = require('./index');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-addons-test-utils');
const chai = require('chai');
const jsdom = require('mocha-jsdom');
const injectTapEventPlugin = require('react-tap-event-plugin');
const nock = require('nock');
const api = require('../../configuration').api;

injectTapEventPlugin();
chai.should();

describe('login', () => {

  beforeEach(() => {
    jsdom();
  });

  it('show error dialog when username or password is invalid', (done) => {
    const login = ReactTestUtils.renderIntoDocument(React.createElement(loginView));

    nock(api).post('user/access-token').reply(200);

    login.setState({
      email: 'test@email.tld',
      password: 'wrong-password'
    });

    ReactTestUtils.Simulate.touchTap(ReactDOM.findDOMNode(login.refs.signin).firstChild);

    setTimeout(() => {
      login.state.showErrorDialog.should.equal(true);
      login.setState({
        showErrorDialog: false
      });
      done();
    }, 1500);
  });
});

点击登录按钮时,ajax 请求检查用户名和密码(使用超级代理)。

问题是我不想使用 setTimeout 函数,我喜欢在 ajax 请求完成时使用回调或承诺。有可能吗?

【问题讨论】:

    标签: testing reactjs mocha.js webpack


    【解决方案1】:

    目前看来使用setTimeout和done是解决这个问题最简单的方法。

    我唯一要改变的是去掉 1500 毫秒的延迟,这是不必要的,因为节点是单线程的。

    【讨论】:

      猜你喜欢
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2020-12-25
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      相关资源
      最近更新 更多