0

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?

M Post
  • 3
  • 2
  • [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Andreas Mar 20 '20 at 13:19

1 Answers1

0

I think you should not return but simply call the $.ajax in the joinGame function as it already invokes resolve/reject when it resolves.

FabioFLX
  • 31
  • 7