I have a method that returns a promise:
joinGame = (playerToken) => {
let p = new Promise((resolve, reject) => {
return $.ajax(_path + '/api/Spel/JoinGame/'+playerToken,
{
method: 'GET',
success: (data) => {
resolve(data);
},
failed: () => {
reject('failed');
}
});
});
return p;
}
I'm using the promise here:
let tokenPromise = SPA.ResponseModule.getPlayerToken;
let gamePromise = SPA.ResponseModule.joinGame;
tokenPromise().then((tokenData) => {
gamePromise(tokenData['playerToken']).then((gameData) => {
...
});
});
The code runs fine when playing the game. The testing code is as follows:
describe("init", () => {
beforeAll(() => {
spyOn(SPA.ResponseModule, "getPlayerToken").and.callFake(() => {
let d = $.Deferred();
let data = {
...
}
d.resolve(data)
return d.promise();
});
spyOn(SPA.ResponseModule, "joinGame").and.callFake((token) => {
let d = $.Deferred();
let data = {
...
};
d.resolve(data);
return d.promise
});
});
beforeEach(() => {
jasmine.Ajax.install();
SPA.init();
});
afterEach(() => {
jasmine.Ajax.uninstall();
});
it ("SPA.ResponseModule's getPlayerToken should be called", () => {
expect(SPA.ResponseModule.getPlayerToken).toHaveBeenCalled();
});
it ("SPA.ResponseModule's joinGame should be called", () => {
expect(SPA.ResponseModule.joinGame).toHaveBeenCalledWith(playerToken);
});
});
50% of the times the second SPA.ResponseModule.joinGame expectation doesnt run OK, 50% of the times it does. For every expectation the SPA.init is ran, in which the promise is used, I get the error gamePromise(...).then is not a function. The problem is supposed to be that the gamePromise does not return a Promise, but it does. What's going wrong here? Should I be mocking the calls?