arisalexis
arisalexis

Reputation: 2210

How can I chain promises sequentially running a mocha integration test?

I want to test two or more promises like an integration test and they should run in sequence. Example is obviously wrong because I get as a user the property from the previous test only (email).

Note that I am using chai-as-promised here but I don't have to if there is a simpler solution.

userStore returns a promise and I can resolve it if its only a one-liner in other tests without a problem.

    it.only('find a user and update him',()=>{
    let user=userStore.find('testUser1');

    return user.should.eventually.have.property('email','[email protected]')
        .then((user)=>{
            user.location='austin,texas,usa';
            userStore.save(user).should.eventually.have.property('location','austin,texas,usa');
        });

});

If I use return Promise.all then it is not guaranteed to run sequentially right?

Upvotes: 3

Views: 1239

Answers (2)

Bergi
Bergi

Reputation: 664630

When chaining promises, you have to ensure to always return the promises from every function, including .then() callbacks. In your case:

it.only('find a user and update him', () => {
    let user = userStore.find('testUser1');
    let savedUser = user.then((u) => {
        u.location = 'austin,texas,usa';
        return userStore.save(u);
//      ^^^^^^
    });
    return Promise.all([
        user.should.eventually.have.property('email', '[email protected]'),
        savedUser.should.eventually.have.property('location', 'austin,texas,usa')
    ]);
});

Upvotes: 1

arisalexis
arisalexis

Reputation: 2210

ES7 with async:

it.only('find async a user and update him',async ()=>{

        let user=await userService.find('testUser1');
        expect(user).to.have.property('email','[email protected]');
        user.location = 'austin,texas,usa';
        let savedUser=await userService.update(user);
        expect(savedUser).to.have.property('location','austin,texas,usa');
});

Upvotes: 0

Related Questions