lundi 22 avril 2019

How can I test a function, returning promises and containing "then"

I'm trying to understand how to use Jasmine for nested promises testing in JS. What will be the approximate scheme to do so? I have a code, that represents an elf's movements. The idea is, to check the reaction of the elf on different gems, e.g. "pirop" in my case. My function consists of chained promises. Can somebody give me a hint, please, how can I test my piece of code, using Jasmine. I've read, that I need to use Jasmine clock, but I can not understand how to do so.

I have already written a test function, but it check only the half of the function (stopping at "then")

Function to test:

function pirop(elf) {
 return new Promise((resolve => {
     setTimeout(() => {
         bothLegsIn(elf);
         bothHandsUp(elf).then(() => {
             bothLegsOut(elf);
             bothHandsDown(elf);
         });
         resolve(elf);
     }, elf.danceSpeed);
 }));
}

Test function:

it("Pirop: legs in, hands up, then legs out, hands down",         function(done) {

  jasmine.clock().install();

    let elf = {
        danceSpeed: 10,
        stance: [0, 0, 0, 0],
    }

    pirop(elf);

    jasmine.clock().tick(200);
    expect(elf.stance).toEqual([1, 1, 1, 1]); //test function successfully check this position, but doesn't move on
    jasmine.clock().tick(40);
    expect(elf.stance).toEqual([0, 0, 0, 0]); //still stays untested
    jasmine.clock().uninstall();
});

The initial posture (stance) is [0, 0, 0, 0]. The final is the same. The stance after "legs in, hands up" will be [1, 1, 1, 1]. So I need to test both postures in one test.

Aucun commentaire:

Enregistrer un commentaire