问题
I really like this resource for AJAX in general and it works in terms of testing a success
or error
function that's within the AJAX parameters.
However, when I instead choose to not have a $.ajax({ ... success: ... })
and choose to have a .done()
outside, I'm not sure how to test. Please help amend my simple spec, thanks!
Code
function itWorked() {}
function sendRequest(callbacks, configuration) {
$.ajax({}).done(function(response) {
itWorked()
});
}
Spec
fdescribe("Ajax Tests", function() {
beforeEach(function() {
spyOn(window, "itWorked")
deferred = $.Deferred().done(function() { })
spyOn($, "ajax").and.callFake(deferred)
sendRequest()
})
it("should work", function() {
expect($.ajax).toHaveBeenCalled() // pass
expect(window.itWorked).toHaveBeenCalled(); // fail
});
});
回答1:
Well, probably the example in the question is not the same you are running local, but it should fail in the line spyOn($, "ajax").and.callFake(deferred)
because callFake
expect a function and deferred
is not. Instead, deferred
should be a resolved Promise and use .and.returnValue
instead of .and.callFake
.
Here is a working example:
function itWorked() {
console.log("It worked!!");
}
function sendRequest(callbacks, configuration) {
$.ajax({}).done(function(response) {
itWorked();
});
}
describe("Ajax Tests", () => {
beforeEach(function() {
spyOn(window, "itWorked").and.callThrough();
deferred = $.Deferred().resolve(); // Call resolve
spyOn($, "ajax").and.returnValue(deferred); // Use return value
sendRequest();
});
it("should work", function() {
expect($.ajax).toHaveBeenCalled(); // pass
expect(window.itWorked).toHaveBeenCalled(); // pass
});
});
Note that I've added console.log("It worked!!");
and use .and.callThrough();
just to double check in the console that "It worked!!" was logged.
When calling $.Deferred().resolve() you can pass a mocked response to deal with in your .done
or .then
callback. Something like .resolve({ success: true })
. Check an example here
Hope it helps
来源:https://stackoverflow.com/questions/53568192/how-to-test-done-part-of-ajax-in-jasmine