首页 > 解决方案 > 模拟 Promise,但在里面运行实际代码然后阻塞

问题描述

我是 javascript 测试框架的新手。我面临一个嘲笑 Promise 的问题。我的代码如下所示:

this.convertEvent(
    () => {
        addUser(this.getProp("criterion")).then((reply) => {
            if (reply[0].m_status === "S") {
                this.getUser();
            }
        });
    });

在我的单元测试中,当我调用 convertEvent 时,我需要执行两个方法 addUser 和 getUser(当回复来自 addUser 时执行)。我正在使用 spyOn() 是这样的:

let thenFunc;
        beforeEach(() => {
            promiseSpyObj.then.and.callFake((func) => {
                thenFunc = func;
                return [{ m_status : "S" }];
            });
            let arrayReply = [{ m_status : "S" }];
            spyOn(className, "addUser").and.returnValue(promiseSpyObj);
            spyOn(className, "getUser").and.returnValue(promiseSpyObj);

我期待: expect(className.addUser).toHaveBeenCalled(); expect(className.getUser).toHaveBeenCalled();

但我注意到只有 addUser() 被调用。我期待的是 addUser 承诺应该解决并且 getUser 应该被调用。

标签: javascriptjasmine

解决方案


首先,你在 spec 中提到的方式, addUser 应该是这样的this.addUser。然后,您的规格可以如下所示:

let reply = [{m_status : "S"}]
spyOn(className, "getUser")
spyOn(className, "addUser").and.returnValue(
    Promise.resolve(reply);
)

className.addUser().then(function () {
    expect(className.getUser).toHaveBeenCalled();
})

此外,您需要查看何时调用convertEvent函数。


推荐阅读