【发布时间】:2019-09-24 01:58:26
【问题描述】:
我正在尝试在打字稿中使用jest 模拟节点模块request 的request() 函数,但我无法做到这一点,有人可以帮我哪里出错了吗?顺便说一句,我正在尝试创建一个通用代理函数,该函数应该适用于所有 http 方法,例如 get、post、delete、update。所以我只想使用request()函数,而不是request.get(),request.post()...等,使用基于请求方法的if-else阶梯。
代理.ts:
import * as request from 'request';
export default class ProxyClass {
static proxy(req: any, res: any): any {
const options: any = {
headers: req.headers,
}
const proxyReq: any = request(options);
proxyReq.on('error', (err: any) => {
return res.status(500).send(err);
});
return proxyReq.pipe(res);
}
}
Proxy.spec.ts:
import 'jest';
import * as request from 'request';
import {Request} from 'jest-express/lib/request';
import {Response} from 'jest-express/lib/response';
import ProxyClass from './Proxy';
describe('proxy request', () => {
const req: any = new Request();
const res: any = new Response();
it('should call pipe', () => {
const mockRequest = {
pipe: jest.fn(),
on: jest.fn(),
}
jest.mock('request', () => {
return function() {
return mockRequest;
}
});
ProxyClass.proxy(req, res);
expect(mockRequest.pipe).toHaveBeenCalledTimes(1);
jest.clearAllMocks();
});
});
当我在上面运行测试时,我收到了错误:
TypeError: request is not a function
【问题讨论】:
标签: node.js typescript jestjs