我在 Vue CLI 应用程序中运行了 Cypress,最近添加了 Mirage 来扩展我的数据库的模拟。我按照Mirage 的快速入门教程在 Cypress 中使用它,现在我正在尝试重新编写我的登录测试。应用程序中的登录与对 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 中的 routes() 挂钩的路由未注册到服务器:
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)
})
})
},
})
}
如果我将 main.js 中的环境“测试”更改为“开发”,则它不会产生影响。
有没有办法在服务器运行时的任何时候查看哪些路由注册到我的服务器?在我的规范中调试服务器时,服务器的路由属性长度为0。我是否在错误的时间或地点定义了我的路由?
更新:我发现当我按照此处所述在 Vue 的 main.js 中创建服务器时,我可以在本地 Web 应用程序中使用有效的 Mirage 路由,而不是使用赛普拉斯框架。所以现在我认为路由定义很好,问题一定在赛普拉斯请求拦截的代码中。