未调用异步回调 jest/supertest - 简单端点
Async callback was not invoked jest/supertest - simple endpoint
我没有调用外部 API 端点,我只是想用 supertest/jest 测试我自己的本地端点。设置超时显然不能解决我的问题,因为这是一个极其简单的请求。我正在根据此请求调用 done,所以我不明白这里出了什么问题。
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:
通常 express Router-level middleware 是用 (req, res, next) 调用的,它们会做一些事情(例如将属性应用于请求或响应)并调用回调而不是 return任何东西。
所以你可能应该模拟它来实际调用 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()
我没有调用外部 API 端点,我只是想用 supertest/jest 测试我自己的本地端点。设置超时显然不能解决我的问题,因为这是一个极其简单的请求。我正在根据此请求调用 done,所以我不明白这里出了什么问题。
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:
通常 express Router-level middleware 是用 (req, res, next) 调用的,它们会做一些事情(例如将属性应用于请求或响应)并调用回调而不是 return任何东西。
所以你可能应该模拟它来实际调用 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()