Mocha + Axios + Sinon + chai单元测试
问题描述:
我有一个反应组件,其功能如下,使用axios调用api服务。我想知道如何使用酶,sinon和chai编写单元测试。Mocha + Axios + 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'
};
请让我知道如何测试爱可信和模拟browserHistory.I我不是在任何浏览器上运行测试,请让我知道如何模拟
谢谢
答
你需要使用如下兴农存根browserHistory
,
import { browserHistory } from 'react-router';
import { stub } from 'sinon';
const browserHistoryPushStub = stub(browserHistory, 'push',() => { });
对于嘲讽爱可信请求,您可以使用Moxios
请再具体些。你是否搜索并尝试了一些解决方案?你遇到了什么问题? – shaochuancs