gpt4 book ai didi

unit-testing - Mocha : Ensure the done() callback is being called in this test

转载 作者:可可西里 更新时间:2023-11-01 16:54:57 25 4
gpt4 key购买 nike

我已经使用 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

还有这个错误:
错误:超时超过 2000 毫秒。确保在此测试中调用了 done() 回调。

编辑:

axios.interceptors.response.use((response) => {
if (response.status === 401) {
storage.clear();
browserHistory.push('/login');
return response;
}
return response;
});

最佳答案

您需要通过在 catch 处理程序中调用 done 将拒绝传递回 Mocha:

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();
}).catch(done);

如果您不处理被拒绝的 promise ,done 可能永远不会被调用(导致超时)。

例如,如果其中一个期望失败,它将抛出一个错误。发生这种情况时,将永远不会执行在预期行之后对 done 的调用。如上所述,您可以(并且应该)使用 .catch 子句捕获错误。那应该调用 done 错误。我使用的代码是以下内容的缩写:

.catch(function(err) {
done(err);
})

关于unit-testing - Mocha : Ensure the done() callback is being called in this test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com