我正在try 使用Jest在NodeJS中为一个函数编写一个测试,该函数一个接一个地调用两个异步函数. 我想延迟Funca,期望函数B不被调用,然后运行计时器并期待函数B被调用.

代码如下所示

//module1.js
async function mainFunc() {
  await module2.funcA()
  await module2.funcB()
}



//module2.js
async function funcA(){
  // making some async operation
}

async function funcB(){
  // making some async operation
}

我试着这样嘲笑Funca的实现:

const spyOnFuncA = jest.spyOn(module2, 'funcA').mockImplementation(async () => new Promise((r) => setTimeout(r, 1000)))

然后在测试中执行如下操作:

  test('Should not call second function until first function resolved', async () => {
    jest.useFakeTimers()
    const spyOnFuncA = jest.spyOn(module2, 'funcA').mockImplementation(async () => new Promise((r) => setTimeout(r, 1000)))
    const spyOnFuncB = jest.spyOn(module2, 'funcB').mockImplementation()

    mainFunc()
    expect(spyOnFuncA).toBeCalled()
    expect(spyOnFuncB).not.toBeCalled()
    
    jest.runAllTimers()
    expect(spyOnFuncB).toBeCalled()
    
  })

我认为这里的问题是jest.useFakeTimers与mock Implementation中的setTimeout相冲突

你知道我该怎么测试这个吗?

会很感激任何 idea

干杯!

推荐答案

模拟funcA返回deferred promise,稍后再解析.我知道SINON提供了promise helper来涵盖延迟,所以JEST可能包括类似的构造.否则,下面就是simple implementations个答案中的一个:

class Deferred {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.reject = reject
      this.resolve = resolve
    })
  }
}

然后,嘲弄是这样的:

    const deferred = new Deferred()
    const spyOnFuncA = jest.spyOn(module2, 'funcA').mockImplementation(() => deferred.promise)
    mainFunc() // avoid uncaught exceptions with `.catch`
      .catch(err => expect(err).toBe(null))
    expect(spyOnFuncA).toBeCalled()
    expect(spyOnFuncB).not.toBeCalled()
    await deferred.resolve('whatever')
    expect(spyOnFuncB).toBeCalled()

Node.js相关问答推荐

如何解决无法获得本地颁发者证书的问题

node 上的磁盘压力

Sequelize-测试使用虚拟场更新模型

在Docker容器404页面中找不到服务器(提供静态reactjs文件)

如何从 Mongo Atlas 触发器向 GCP PubSub 发出经过身份验证的请求

Typescript 正则表达式:过滤器返回空

我如何在 Raku 的供应中注册不同的事件?

错误:0308010C:try 通过 Github 推送部署到 firebase 托管时出现数字

Nodejs mongoose 在一个查询中从多个集合中获取结果

将 AllowDiskUse true 添加到 node.js 中的 MongoDB 聚合?

'{ id: string; 类型的参数}' 不可分配给FindOneOptions类型的参数

GridFS 大文件下载使 Node.js 服务器崩溃. MongoServerError:排序超出了字节的内存限制

如何promise AWS JavaScript 开发工具包?

node.js 中 res.setHeader 和 res.header 的区别

如何在 Node.js 的 console.log() 中创建换行符

如何将使用 Gulp 的 node 部署到 heroku

Node.js、Cygwin 和 Socket.io 走进一家wine 吧……Node.js 抛出 ENOBUFS,所有人都死了

使用 MongoDB 更新嵌套数组

安装 node 包时可以使用自定义目录名称而不是node_modules吗?

使用 Node.js 我得到错误:EISDIR,读取