javascript - 模拟 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 应该被调用。
解决方案
首先,你在 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
函数。
推荐阅读
- python - Is it possible to make my own encryption when sending data through sockets?
- python - Select columns by (iloc) name in pandas
- arduino - 从 MPU-9250 获取航向/方向
- jquery - 过滤没有 lambda 符号的 JSON
- typescript - 每60秒获取一次http请求Angular 6
- unity3d - Unity 游戏对象控制器
- google-chrome-devtools - Puppeteer 中的 HeadlessExperimental
- python - 找出在哪个版本的 numpy 上添加了函数
- tabulator - 从文本文件加载表数据
- java - Spring WebFlux | 用于检测未使用的 Mono / Flux 的静态代码分析工具