【发布时间】:2017-03-12 09:18:46
【问题描述】:
我使用axios 编写了一个小型拦截器,它将清除localBrowserStorage,如果响应代码为401,则将用户重定向到登录页面。
它工作正常,但我在单元测试中遇到了一些错误。
测试
describe('Api Service', () => {
let sandbox;
beforeEach(() => {
moxios.install();
sandbox = sinon.sandbox.create();
});
afterEach(() => {
moxios.uninstall();
sandbox.restore();
});
describe.only('interceptors', () => {
it('clear storage and redirect to login if response status code is 401', (done) => {
moxios.withMock(() => {
sandbox.spy(browserHistory, 'push');
sandbox.spy(storage, 'clear');
axios.get('/test');
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 401,
response: {}
}).then(() => {
expect(browserHistory.push).to.have.been.calledWith('/login');
expect(storage.clear).to.have.been.called; // eslint-disable-line no-unused-expressions
done();
});
});
});
});
});
});
我收到这两个警告:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 401
(node:5338) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): AssertionError: expected push to have been called with arguments /login
还有这个错误:Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
编辑:
axios.interceptors.response.use((response) => {
if (response.status === 401) {
storage.clear();
browserHistory.push('/login');
return response;
}
return response;
});
【问题讨论】:
标签: unit-testing http mocha.js sinon axios