如何使用 proxyquire 模拟“请求”
Posted
技术标签:
【中文标题】如何使用 proxyquire 模拟“请求”【英文标题】:How to mock 'request' with proxyquire 【发布时间】:2021-10-02 07:48:41 【问题描述】:我有一个文件foo.js
var request = require('request');
module.exports.getRequest = function (url, headers)
return new Promise((resolve, reject) =>
request(
url: url,
method: "GET",
timeout: 30000,
headers: headers,
,
function (error, response, body)
if (error)
reject(error);
resolve(response, body);
);
);
;
我想为它写一个测试用例。但我不能写。 有人可以帮忙吗? 我尝试过这样的事情。
var proxyquire = require('proxyquire')
, assert = require('assert')
, pathStub = ;
describe('Test', () =>
it('1', () =>
var foo = proxyquire('./foo', 'request': pathStub);
pathStub.request = function (file, option)
console.log("Request Stub");
option(null, "a", "b");
;
let b = foo.getRequest('file.txt');
assert.strictEqual(foo.getRequest('file.txt'), 'EXTERMINATE, EXTERMINATE THE FILE.TXT');
);
);
错误 - (node:15344) UnhandledPromiseRejectionWarning: TypeError: request is not a function
【问题讨论】:
【参考方案1】:您没有正确存根 request
函数。
例如
foo.js
:
var request = require('request');
module.exports.getRequest = function (url, headers)
return new Promise((resolve, reject) =>
request(
url: url,
method: 'GET',
timeout: 30000,
headers: headers,
,
function (error, response, body)
if (error)
reject(error);
resolve( response, body );
,
);
);
;
foo.test.js
:
var proxyquire = require('proxyquire'),
assert = require('assert');
describe('Test', () =>
it('1', async () =>
const requestStub = function (option, callback)
console.log('Request Stub');
callback(null, 'a', 'b');
;
var foo = proxyquire('./foo', request: requestStub );
var actual = await foo.getRequest('file.txt');
assert.deepStrictEqual(actual, response: 'a', body: 'b' );
);
);
单元测试结果:
Test
Request Stub
✓ 1 (1378ms)
1 passing (1s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 85.71 | 50 | 100 | 85.71 |
foo.js | 85.71 | 50 | 100 | 85.71 | 14
----------|---------|----------|---------|---------|-------------------
【讨论】:
以上是关于如何使用 proxyquire 模拟“请求”的主要内容,如果未能解决你的问题,请参考以下文章