我正在尝试测试将在 Promise 的 .then
block 中调用的 spy ,但是 then
中的 done
> block 似乎根本没有被执行。
我超时超过 2000 毫秒。
这是我正在测试的内容(异步):
/**
* Passed down to the LoginForm component to
* handle form submission.
*/
_submitHandler(data) {
return function(evt) {
evt.preventDefault && evt.preventDefault();
evt.stopPropagation && evt.stopPropagation();
return request('post', 'auth', data)
.then((res) => {
AuthActions.login();
return res;
})
}
}
这是我的测试:
describe('when it succeeds', () => {
it('should login', (done) => {
sinon.spy(AuthActions, 'login');
Instance._submitHandler({})({})
.then((res) => {
console.log('Called!!!');
expect(AuthActions.login.called).to.equal(true);
AuthActions.login.restore();
done();
}, done);
});
});
我正在使用 Karma 来运行我的测试;柴和诗浓。
最佳答案
我也遇到了这个问题,原因是在连接打开之前尝试响应 XHR,例如
此代码将从 FakeXMLHttpRequest.setResponseHeaders
抛出 INVALID_STATE_ERR - 0
:
describe("get", function () {
beforeEach(function () {
this.xhr = sinon.useFakeXMLHttpRequest();
this.xhr.onCreate = function (request) {
request.respond(200, null, "");
};
});
afterEach(function () {
this.xhr.restore();
});
it("should make a request", function () {
myObject.get("testurl");
});
});
此代码有效:
describe("get", function () {
beforeEach(function () {
this.xhr = sinon.useFakeXMLHttpRequest();
this.requests = [];
this.xhr.onCreate = function (request) {
this.requests.push(request);
};
});
afterEach(function () {
this.xhr.restore();
});
it("should make a request", function () {
myObject.get("testurl");
this.requests[0].respond(200, null, "");
});
});
阅读文档(它本身确实显示了推送到请求数组的相同技术),我下意识地、不准确地得到了这样的印象:onCreate,尽管它的名字,更像是“根据请求”。
myObject.get = function (url) {
var http = new XMLHttpRequest();
// the XHR instance exists
// readyState is 0
// onCreate runs now
http.open("GET", url);
http.send();
// readyState is 1
// can call setResponseHeaders and respond
}
结果是,您必须在调用运行 XMLHttpRequest
的 send
的方法后放置响应代码,如下所示:
myObject.get("testurl");
this.requests[0].respond(200, null, "");
我使用的是respond
方法,但setResponseHeaders
也是如此(respond
调用setResponseHeaders
) --在你的测试中它被调用得太早了。
关于javascript - Mocha - 测试 Promise, `done` 永远不会在 Promise 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810939/