Reputation: 1954
I am currently starting a project that I would love to do using react js. But before I can start I need to figure out a good workflow including unit test, etc. The first problem that I have is that Jest has currently a bug that it makes it crash a soon as you require("jquery"). Since I couldn't find a way to debug Jest tests anyway I decided to try using karma with jasmine. The problem that I am now having is that when I try to test an ajax call I never get a response.
The current variation for the service is:
var _isTesting = false;
var deferred;
var TestService = {
loginUser:function(username, password){
var data = {
username: username,
password: password
};
console.log("calling ajax");
return ($.ajax({
type: "POST",
url: "https://test.com/service",
data:data,
dataType:"json"
}));
}
};
module.exports =TestService;
And the test looks like this:
describe('TestService', function(){
var onSuccess, onFailure, request;
var service = {};
beforeEach(function(){
jasmine.Ajax.install();
service = require("../js/services/TestService");
onSuccess = jasmine.createSpy('onSuccess');
onFailure = jasmine.createSpy('onFailure');
});
it('should set the testing variable', function(){
expect(service.getIsTesting()).toBe(false);
service.setIsTesting(true);
expect(service.getIsTesting()).toBe(true);
});
it('should log in', function(){
var def = service.loginUser("username", "password");
def.done(function(result){
console.log("#######" + JSON.stringify(result))
onSuccess(result);
})
.fail(function(error){
console.log("#### ERROR ###"+JSON.stringify(error));
onFailure(error);
});
request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe("https://test.com/service");
expect(request.method).toBe('POST');
expect(onSuccess).toHaveBeenCalled();
})
});
The firs to expects are successful but the third one fails, that is I never get a response from the ajax call.
Any ideas?
Upvotes: 0
Views: 569
Reputation: 362
Looking at the Jasmine docs (http://jasmine.github.io/2.2/ajax.html), you need to tell the framework to return data from the mocked AJAX call - it doesn't automatically respond with anything. Try something like:
....
expect(request.method).toBe('POST');
//respond to AJAX call
request.respondWith({
"status": 200,
"responseText": "some return data"
});
//now check that your success method was called
expect(onSuccess).toHaveBeenCalled();
As an aside on Jest - it doesn't currently support aliases, which is why your require('jquery')
call won't work. (see this pull request: https://github.com/facebook/jest/pull/237). I haven't tried this, but you might get Jest working if you use a full path to require jquery instead of the alias. Something like require('../node_modules/jquery');
It's annoying though, which is why I'm probably going to go with Karma/Jasmine as well for a new project.
Upvotes: 1