我已经搜索了很多,尽管有很多关于模拟功能的问题,但我发现没有一种解决方案可用于我的设置,而且我不确定为什么。我有以下内容:
questionnaire-service.js
const service = require('./request-service')();
function questionnaireService() {
function createQuestionnaire() {
const opts = {
url: `http://some-url.com`,
body: {
data: "some-data"
}
};
return service.post(opts);
}
return Object.freeze({
createQuestionnaire
});
}
module.exports = questionnaireService;
request-service.js
const got = require('got');
const merge = require('lodash.merge');
function requestService() {
function post(options) {
let opts = {
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json'
},
json: true,
body: options.body
};
opts = merge(opts, options);
return got(opts.url, opts);
}
return Object.freeze({
post
});
}
module.exports = requestService;
我正在尝试为问卷调查服务编写测试,并希望模拟“发布”功能。我尝试了以下
questionnaire-service.test.js
const requestService = require('./request-service')();
const questionnaireService = require('./questionnaire-service')();
const createdQuestionnaire = require('./test-fixtures/res/get_questionnaire.json');
describe('questionnaire service routes', () => {
it('Should create a new questionnaire', async () => {
const spy = jest.spyOn(requestService.post);
spy.mockReturnValue(createdQuestionnaire);
const response = await questionnaireService.createQuestionnaire();
expect(requestService.post).toBeCalled();
expect(response).toMatch(createdQuestionnaire);
}
it('Should create a new questionnaire', async () => {
jest.doMock('./questionnaire-service', () =>
jest.fn(() => ({
createQuestionnaire: () => createdQuestionnaire
}))
);
const response = await questionnaireService.createQuestionnaire();
expect(questionnaireService.createQuestionnaire).toBeCalled();
expect(response).toMatch(createdQuestionnaire);
}
it('Should create a new questionnaire', async () => {
jest.doMock('./request-service', () =>
jest.fn(() => ({
post: () => createdQuestionnaire
}))
);
const response = await questionnaireService.createQuestionnaire();
expect(requestService.post).toBeCalled();
expect(response).toMatch(createdQuestionnaire);
}
});
以上所有都产生相同的错误:RequestError: getaddrinfo ENOTFOUND some_token some_token:443
听起来像是被'GOT'模块抛出而找不到要命中的URL。有人可以阐明如何使其正常工作吗?
答案 0 :(得分:1)
创建require("somemodule")
时,它将加载并执行该模块,因此它将在此模块内执行require
调用。然后,所有模块都被缓存,因此无论何时再次创建require
,它都不会再次执行,并返回已缓存的依赖项。
执行doMock
时,需要重置此缓存,并在测试中为所有内容创建新的require
,这取决于模拟的模块。
jest.doMock('./questionnaire-service', () =>
jest.fn(() => ({
createQuestionnaire: () => createdQuestionnaire
}))
);
jest.resetModules();
const questionnaireService = require(`questionnaire-service`)();
const response = await questionnaireService.createQuestionnaire();