我在Vue CLI应用程序中运行了Cypress,最近又添加了Mirage,以扩展数据库的模拟功能。我按照Mirage的快速入门指南在赛普拉斯中使用它,现在我正尝试重新编写我的登录测试。应用程序中的登录与对API端点/ oauth / token的POST请求一起使用,但在Cypress / Mirage中失败,提示
"Mirage: Your app tried to POST 'http://localhost:8090/oauth/token', but there was no route defined to handle this request. Define a route for this endpoint in your routes() config. Did you forget to define a namespace?"
似乎server.js中来自route()挂钩的路由未注册到服务器:
import { Server, Model } from 'miragejs'
export function makeServer({ environment = 'development' } = {}) {
let server = new Server({
environment,
models: {
user: Model,
},
seeds(server) {
server.create("user", { name: "Bob" })
server.create("user", { name: "Alice" })
},
routes() {
this.urlPrefix = 'http://localhost:8090'
this.namespace = ''
/* Login */
this.post("/oauth/token", () => {
return { 'access_token': 'abcd123456789', 'token_type': 'bearer', 'refresh_token': 'efgh123456789'}
})
}
})
return server
}
在规范文件的beforeEach挂钩中,我调用了服务器函数:
import { makeServer } from '../../src/server'
let server
beforeEach(() => {
server = makeServer({ environment: 'development' })
})
并且我还将本块添加到了cypress / support / index.js中,如本教程所述:
Cypress.on("window:before:load", (win) => {
win.handleFromCypress = function (request) {
return fetch(request.url, {
method: request.method,
headers: request.requestHeaders,
body: request.requestBody,
}).then((res) => {
let content =
res.headers.map["content-type"] === "application/json"
? res.json()
: res.text()
return new Promise((resolve) => {
content.then((body) => resolve([res.status, res.headers, body]))
})
})
}
})
然后我将此块添加到Vue的main.js中:
import { Server, Response } from "miragejs"
if (window.Cypress) {
new Server({
environment: "test",
routes() {
let methods = ["get", "put", "patch", "post", "delete"]
methods.forEach((method) => {
this[method]("/*", async (schema, request) => {
let [status, headers, body] = await window.handleFromCypress(request)
return new Response(status, headers, body)
})
})
},
})
}
如果我将其更改为“ development”,则main.js中的“ test”环境不会有所作为。
有什么方法可以查看在服务器运行时的任何时间向我的服务器注册了哪些路由?在规范中调试服务器时,服务器的路由属性的长度为0。我在错误的时间或地点定义了路由吗?
更新:我发现,当我按此处所述在Vue的main.js中制作服务器时,可以使用本地Web应用程序中的有效Mirage路由,而不是使用Cypress框架。因此,现在我认为路由定义很好,问题必须在赛普拉斯请求拦截的代码内。
我终于在Mirage不和谐频道上的Sam Selikoff的帮助下找到了解决方案。我的问题是我的API与我的应用程序在不同的端口上运行。
正如山姆(Sam)在不和中所说(我对此稍作表述):
默认情况下,
this.passthrough()
仅适用于当前域上的请求。Vue main.js快速入门第4步中的代码需要说明this[method]("http://localhost:8090/*", async...
代替
this[method]("/*", async...
我希望这会在将来对某人有所帮助。我花了整整一个星期的时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句