如何模拟具有绝对路径的请求以进行JS测试
How to mock requests with absolute path for JS testing?
在一个组件中,我向"/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 字符串解决了这个问题。
相关文章:
- 请求准备一个文件并返回路径,允许用户在准备好时下载
- 如何模拟具有绝对路径的请求以进行JS测试
- Javascript:终止不是来自特定路径的请求或直接请求
- 使用 JS 更改映像路径的请求错误
- Javascript 无法解析正确的图像路径,当使用 URL 路由在 ASP.Net 中请求页面时
- Rails:我可以将GET请求发送到创建路径吗?
- 如果请求中已提供 URI 的“路径”部分,则跳过该部分
- HTTP 请求中的角度相对路径
- 节点.js:从请求中获取路径
- 如何使用node/express将每个无效请求路由到默认路径
- 路径参数或请求参数-从客户端角度
- 对从AJAX发送到我的Express服务器的请求路径感到困惑
- TypeError:请求路径包含未转义的字符
- 在ajax请求中隐藏php文件的路径
- POST请求是如何在jQuery中使用相对路径的?
- 为什么在Durandal Get started教程中,text.js的请求路径错误?
- 如果路径中有一个querystring, Firefox是否缓存javascript并在没有请求的情况下使用它?
- 在nodejs中从请求的路由中获取其余的路径
- 替换浏览器中的URL路径,而不是请求中的路径
- 从请求中获取文件路径