【问题标题】:Async callback was not invoked jest/supertest - simple endpoint未调用异步回调 jest/supertest - 简单端点
【发布时间】:2020-12-16 21:53:01
【问题描述】:

我没有调用外部 API 端点,我只是想用 supertest/jest 测试我自己的本地端点。设置超时显然不会解决我的问题,因为这是一个非常简单的请求。我正在按此请求调用完成,所以我不明白这里有什么问题。

router.get('/photo', Photo.getFromRequest, function (request, res) {
  // making this simple just for the first step
  return res.status(200).send
})
jest.mock('../models/photo', () => ({
  getFromRequest: jest.fn().mockReturnValueOnce({ id: xxx })
}))

const photo = require('./photo')
const request = require('supertest')
const express = require('express')

const app = express()
app.use('/', photo)
describe('validate photo endpoint', () => {
  it('returns 200 and object photo link/image', function (done) {
    request(app)
      .get('/photo')
      // assert things later
      .end(function (err, res) {
        done(err)
      })
  })
})
   : Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 30000 ms timeout specified by jest.setTimeout.Error:

【问题讨论】:

  • 在该示例中,没有中间件会失败,因为您从不发送响应 - 您在 .send 上缺少括号。请注意,您不需要来自中间件的模拟返回值 - 不使用返回值。
  • 好地方,但仍然失败..
  • 出于同样的原因?请更新以提供minimal reproducible example

标签: node.js express jestjs timeout supertest


【解决方案1】:

通常使用 (req, res, next) 调用 express Router-level middleware,它们执行某些操作(例如将属性应用于请求或响应)并调用回调并且不返回任何内容。

因此,您可能应该模拟它以实际调用 next 回调,如下所示:

jest.mock('../models/photo', () => ({
  getFromRequest: jest.fn().mockImplementation((req, res, next) => {
    req.photo = { id: xxx };
    next();
  })
}))

编辑:检查中间件是否已被调用,您也可以在测试中导入它

import { getFromRequest } from '../models/photo'

// ...your mock and other tests here
// and after you've executed the request you may assert
expect(getFromRequest).toHaveBeenCalled()

【讨论】:

  • 谢谢!我尝试了这个实现一段时间,但我可以看到我很接近。我如何使用它来期望(中间件).toHaveBeenCalledTimes(1)。将它分配给一个变量并在这个期望中使用它是行不通的..
猜你喜欢
  • 1970-01-01
  • 2020-03-09
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2020-11-17
  • 2012-03-12
相关资源
最近更新 更多