Node.js 如何使用Nock,Node js模拟单元测试中的一行
我试图在单元测试中插入一行代码,但失败了,它似乎遇到了一个真正的请求,下面的代码是足球api的一部分,我需要模拟这个文件中的最后一行Node.js 如何使用Nock,Node js模拟单元测试中的一行,node.js,unit-testing,chai,nock,Node.js,Unit Testing,Chai,Nock,我试图在单元测试中插入一行代码,但失败了,它似乎遇到了一个真正的请求,下面的代码是足球api的一部分,我需要模拟这个文件中的最后一行 module.exports.getSummary = async ({ uuid, market}) => { const { countryCode } = AppConfigs.Markets[market]; let url = `${host}${getSummary}`; url = url.replace('[market]',
module.exports.getSummary = async ({ uuid, market}) => {
const { countryCode } = AppConfigs.Markets[market];
let url = `${host}${getSummary}`;
url = url.replace('[market]', countryCode);
url = url.replace('[uuid]', uuid);
Log.debug('Getting Summary Info from football API', { url }, 'Subscription::index', 'info');
// this line which i need to inject
const result = await Helpers.http.get({}, url, undefined);
return result;
};
这是我试过的模拟
const chai = require('chai');
const nock = require('nock');
const FootballApi = require('../../server/services/football/index');
const SummaryMock = require('./getSummary.mock');
const { expect } = chai;
describe('get Summary', () => {
it('Should return null', async () => {
before(() => {
const { req, res } = SummaryMock.getSummary;
const mock = nock(FootballApi.getSummary(req));
mock.get(req.path).reply(200, res);
});
const { res } = SummaryMock.getSummary;
const response = await FootballApi.getSummary(SummaryMock.getSummary.req);
console.log(response);
console.log(res);
});
});
看来我误解了诺克的所作所为。 这就是诺克的工作原理 您需要模拟主机url。 您需要模拟路径,使用任何http方法,但它应该与 现有url甚至包括查询参数。 之后,Nock将尝试组合它们,并查看是否有匹配的url 例如 我们的主持人是:http://www.example.com 我们的路径是:/uuid/training 那么我们应该做些类似的事情
const mockHttp = nock(training.baseUrl); //mock the http
mockHttp.get(ourPath).reply(200, ourBody); //mock exact path
现在,如果Nock看到匹配的url,那么Nock将像charm一样工作,否则它将抛出一个与特定url不匹配的异常Nock