我有一个网络应用程序需要检查用户是否连接到互联网.在实现中,如果对已知端点的ajax ping成功,则check()函数将为true,如果ajax调用以任何方式失败,则为false.
在Jasmine中,我可以request.respondWith({status:400, etc})用来模拟失败,但我无法弄清楚如何模拟根本没有发出的更基本的错误.
实际上,当甚至无法进行调用时,浏览器似乎"返回"状态代码0和readyState 4.
我应该如何在Jasmine测试中解决这个问题?
我正在使用 Jasmine 2.5.2 为使用 jQuery 3.1.1 执行 Ajax 请求的代码编写单元测试。我想模拟 Ajax 调用,提供我自己的响应状态和文本。
我正在使用 Jasmine ajax 插件 ( https://github.com/pivotal/jasmine-ajax )。
按照https://jasmine.github.io/2.0/ajax.html上的示例,它使用 XMLHttpRequest 对象,效果很好。
describe("mocking ajax", function() {
describe("suite wide usage", function() {
beforeEach(function() {
jasmine.Ajax.install();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it("specifying response when you need it", function() {
var doneFn = jasmine.createSpy("success");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(args) {
if (this.readyState == this.DONE) {
doneFn(this.responseText);
}
};
xhr.open("GET", "/some/cool/url");
xhr.send();
expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
expect(doneFn).not.toHaveBeenCalled();
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'text/plain',
"responseText": …Run Code Online (Sandbox Code Playgroud)