异步回调未调用jest/supertest-简单端点



我不是在调用外部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:

通常使用(req,res,next(调用express Router级中间件,它们会执行某些操作(例如将属性应用于请求或响应(并调用回调,但不会返回任何内容。

因此,您可能应该模拟它实际调用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()

最新更新