如何使用proxyquire模拟“请求”

gmxoilav  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(323)

我有一份档案 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');
});

});

错误-(节点:15344)未处理的PromisejectionWarning:typeerror:请求不是函数
ckocjqey

ckocjqey1#

你没有 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% LinesUncovered Line #s
------------------------------------------------------------------
All files85.715010085.71
foo.js85.715010085.7114
------------------------------------------------------------------

相关问题