【问题标题】:How can I chain promises sequentially running a mocha integration test?如何按顺序运行 mocha 集成测试?
【发布时间】:2015-11-24 04:22:51
【问题描述】:

我想像集成测试一样测试两个或多个 Promise,它们应该按顺序运行。示例显然是错误的,因为我作为用户仅从上一个测试中获得了属性(电子邮件)。

请注意,我在这里使用 chai-as-promised,但如果有更简单的解决方案,我不必这样做。

userStore 返回一个 Promise,如果它在其他测试中只有一个单行,我可以解决它。

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

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

});

如果我使用 return Promise.all 则不能保证按顺序运行,对吗?

【问题讨论】:

    标签: javascript node.js ecmascript-6 es6-promise


    【解决方案1】:

    当链接承诺时,您必须确保总是return来自每个函数的承诺,包括.then()回调。在你的情况下:

    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', 'testUser1@email.com'),
            savedUser.should.eventually.have.property('location', 'austin,texas,usa')
        ]);
    });
    

    【讨论】:

    • 我试过了,但是第二个链式承诺中的用户参数是字符串'testUser1@email.com',它可能是从 chai should 返回的。
    • @arisalexis:你能试试Promise.all([user, user.should.eventually.…]).then(([user]) => … )吗?
    • 所以测试不同东西的关键是保留一个参考,比如你想要测试的承诺的快照。这就是我想要的。
    • @Bergi - “..你必须确保总是 return promises..”。事实并非如此,因为then() 会将函数的返回值映射到一个 Promise 中,即使它是一个通用值。例如:Promise.resolve('done') .then(function(value) { return 'Yabadabadoo'; }) .then(console.log.bind(console)) // Yabadabadoo .catch(console.error.bind(console));
    • @caasjj:当然可以。我的意思是你总是需要返回承诺当函数执行异步操作时,我在这里省略了这个子条款,因为问题中的所有函数都是异步的。
    【解决方案2】:

    带异步的 ES7:

    it.only('find async a user and update him',async ()=>{
    
            let user=await userService.find('testUser1');
            expect(user).to.have.property('email','testUser1@email.com');
            user.location = 'austin,texas,usa';
            let savedUser=await userService.update(user);
            expect(savedUser).to.have.property('location','austin,texas,usa');
    });
    

    【讨论】:

    • 我认为es7被称为?我只是把当前年份放在了可见的地方。不知道怎么格式化。
    • 是的,ES7 == ES2016。但不要将两者混为一谈 :-)
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2012-04-01
    • 2016-07-17
    • 2015-12-21
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多