我使用requestjs向API发出get请求,然后在requestCallBack中将主体映射到自定义的json对象。我试着用Jest测试这段代码,但不管我怎么嘲弄它,它似乎都不起作用
我尝试过request.get.mockImplementation(),这似乎只是在嘲笑get,而不允许我在回调中测试代码
await request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) }) jest.mock('request')
jest.mock('request-promise-native')
import request from 'request-promise-native'
test('test requestCallback code', async () => {
// not sure how to test that bodyTransformer is called and is working
}发布于 2019-01-11 01:05:07
您可以使用mockFn.mock.calls获得模拟调用的参数。
在本例中,request.get是一个模拟函数(因为整个request-promise-native是自动嘲弄),所以您可以使用request.get.mock.calls来获取调用它的参数。第三个参数将是您的回调,因此您可以检索它,然后像这样测试它:
jest.mock('request-promise-native');
import request from 'request-promise-native';
test('test requestCallback code', () => {
request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) });
const firstCallArgs = request.get.mock.calls[0]; // get the args the mock was called with
const callback = firstCallArgs[2]; // callback is the third argument
// test callback here
});https://stackoverflow.com/questions/54138867
复制相似问题