Mocha+Axios+Sinon+chai 单元测试

Mocha+Axios+Sinon+chai unit testing

我有一个 React 组件,其功能如下,使用 axios.I 调用 api 服务想知道如何使用酶、sinon 和 chai 编写单元测试。

import React from 'react';
import es6BindAll from 'es6bindall';
import { browserHistory } from 'react-router';
import axios from 'axios';

export default class Header extends React.Component {
    constructor() {
        super();
        es6BindAll(this,['handleLogoutClick']);
    }
    handleLogoutClick(e) {
        e.preventDefault();
        let that = this;
            this.serverRequest = axios({
                url: 'Url_to_call',
                method: 'post'
            }).then(function (successData) {
                browserHistory.push("nextPage to navigate");                
            }.bind(that));
    }
    render(){
        return(
            <div className="columns large-12 header-container">
                <h6 className="logout" onClick={this.handleLogoutClick}>Logout</h6>
                </div>
            </div>
        )
    }
}

我写的测试用例如下

import React from 'react';                
import { mount,shallow } from 'enzyme';          
import { expect } from 'chai';  
import sinon from 'sinon';
import '../testUtils';
import Header from '../../components/Common/Header'; 

describe('(Container) Header', () => {
 const wrapper = shallow(<Header />);
let sandbox;
  let server;
  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    server = sandbox.useFakeServer();
  });
  afterEach(() => {
    server.restore();
    sandbox.restore();
  });

   it('Logout link to be present', () => {
    expect(wrapper.find('.logout')).to.exist;
  });
  it('simulates logout clicks', () => {         

    wrapper.find('h6').filter('.logout').simulate('click',{preventDefault() {} });
        expect(wrapper.instance().handleLogoutClick).to.have.been.called;

  });
});

并配置testUtils.js如下

var jsdom = require('jsdom').jsdom;

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    global[property] = document.defaultView[property];
  }
});
global.window.loggedInUserData = {userName: 'TestName'};
global.navigator = {
  userAgent: 'node.js'
};

请让我知道如何测试 axios 和 mock browserHistory.I 我不能 运行 在任何浏览器上进行测试所以请让我知道如何模拟

谢谢

您需要使用 sinon 存根 browserHistory,如下所示,

import { browserHistory } from 'react-router';
import { stub } from 'sinon';
const browserHistoryPushStub = stub(browserHistory, 'push', () => { });

对于模拟axios请求,你可以使用Moxios