如何模拟具有绝对路径的请求以进行JS测试

How to mock requests with absolute path for JS testing?

本文关键字:请求 路径 测试 JS 何模拟 模拟      更新时间:2023-09-26

在一个组件中,我向"/api/somecall"发送了一个xhr请求

我正在尝试用MochaJS模拟HTTP请求以进行测试。

我进入了nock,但第一个参数是域,无法修复,因为我们在多个域上使用相同的应用程序。

我想用 location.href 嘲笑一个 DOM,以便在 Mocha 的测试会话开始时以这种方式将 xhr 发送到一个特定的域,就像这样(我在网络上找到了这段代码的一部分):

// setup the simplest document possible
var doc = jsdom.jsdom('<!doctype html><html><body></body></html>', {url: "http://localhost"})
// get the window object out of the document
var win = doc.defaultView
// set globals for mocha that make access to document and window feel 
// natural in the test environment
global.document = doc
global.window = win
// take all properties of the window object and also attach it to the 
// mocha global object
propagateToGlobal(win)
// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal (window) {
  for (let key in window) {
    if (!window.hasOwnProperty(key)) continue
    if (key in global) continue
    global[key] = window[key]
  }
}

不幸的是,当我之后尝试此操作时,它仍然不起作用:

nock('http://localhost')
      .get('/apv/v2/listings/' + county)
      .reply(200, responseData)

所有测试都像以前一样返回一个请求 tiemout。

我怎么可能让它工作?

由于某些原因,问题是路径添加了非 ASCII 字符,因此使用正则表达式路径而不是 plein 字符串解决了这个问题。