相对 URL 作为 Nock 中的主机名

Relative URL as hostname in Nock

我需要模拟客户端 HTTP 请求。我在客户端使用 isomorphic-fetch 并使用 mochanock 进行测试和模拟。我所有的客户请求都是基于相对路径的。因此,我无法为 nock 提供主机名。有解决办法吗。

客户端:

fetch('/foo') //hostname: http://localhost:8080
.then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log(e))

测试套件

nock('/')
.get('/foo')
.reply(200, {data: "hello"})

这是失败的,因为我没有为 nock 提供正确的主机名。我做错了什么吗?

我刚刚在 Nock 的存储库上问了一个类似的问题。显然这不受支持:https://github.com/pgte/nock/issues/431

找到解决方法。在你的测试文件夹中有一个 _ajax-setup.js

import $ from 'jquery'

$(document).ajaxSend((event, jqxhr, settings) => {
  settings.url = 'http://0.0.0.0' + settings.url;
})

需要注意的是这个文件必须运行第一个Only Once。将其作为文件 运行 只使用一次,并且 _ 在它按字母顺序排在第一位之前。

稍后您可以使用

测试您的代码
nock('http://0.0.0.0')
.get('/foo')
.reply(200, {data: "hello"})

对于任何感兴趣的人:在我的 react/webpack 项目中,当 NODE_ENV 设置为 'test'.

示例:

const testing = process.env.NODE_ENV === 'test';
const apiUrl = `${testing ? 'http://localhost' : ''}/api`;

function getStuffFromApi() {
  return fetch(apiUrl, ...)
}

这样,在我的测试中我总是可以像这样使用箭尾:

nock('http://localhost')
  .get('/api')
  .reply(200, {data: 'hello'})

注意:当 运行 我的测试时,NODE_ENV 设置为 'test'

对于 axios,我在测试文件中添加了以下内容。这有助于克服此限制。

    axios.defaults.baseURL='http://localhost:4000/';

请注意这是一个全局变量。 有了这个,实际代码可以与相对 URL 一起使用,并且不需要检查其中的测试标志。

kudresov 对 liorbauer's issue 的回复描述了 Jest 特定的解决方法。

Put this into __mocks__/isomorphic-fetch.js:

const fetch = require.requireActual('isomorphic-fetch');

module.exports = (url, config) => {
  return fetch('https://localhost' + url, config);
};

Jest then automatically replaces all requires (or imports) for this node module.

In other test frameworks you could use something like rewire