我已经为控制器创建了一个单元测试用例,并在运行测试用例时模拟请求、响应和下一步,它会抛出笑话超时错误。
谁能帮我解决这个问题。
员工.controller.ts
import { Request, Response, NextFunction } from 'express';
import { employeeService } from './employee._service';
const empServices = new employeeService();
module employeeController {
export async function getEmployee(req: Request, res: Response, next: NextFunction) {
try {
const result = await empServices.getEmployee();
res.send(result);
return result;
}
catch (err) {
console.log(err);
res.statusCode = 200;
res.send("error in getEmployee: " + err);
};
};
}
export { employeeController }
员工.controller.spec.ts
import { Request, Response, NextFunction } from 'express';
import { employeeController } from '../employee.controller';
import { employeeService } from '../employee._service';
describe("should return pong message", () => {
const service = new employeeService();
it("should return pong message", async () => {
const mockRequest: any = {
body: jest.fn(),
params: jest.fn()
};
const mockResponse: any = {
json: jest.fn(),
status: jest.fn(),
};
const mockNext: NextFunction = jest.fn();
const spy = jest.spyOn(service, 'getEmployee').mockResolvedValueOnce([]);
const comments = await employeeController.getEmployee(mockRequest, mockResponse, mockNext);
expect(comments).toEqual([]);
expect(spy).toHaveBeenCalledWith()
expect(spy).toHaveBeenCalledTimes(1)
});
});
谢谢
对我有用的一种方法是将超时值增加到适合您需要的数字; 在此示例中为 60 秒:
beforeEach((): void => {
jest.setTimeout(60000);
...
});
对于 CRA 用户,我们可以将
jest.setTimeout(ms)
放入 setupTests
文件中,以增加全局超时,以防其他测试因相同原因失败。