J. *_*ass 9 automated-tests vue.js mirage vue-cli cypress
我在 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?"
Run Code Online (Sandbox Code Playgroud)
看起来好像来自 server.js 中的 paths() 挂钩的路由没有注册到服务器:
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
}
Run Code Online (Sandbox Code Playgroud)
在规范文件的 beforeEach 挂钩中,我调用服务器函数:
import { makeServer } from '../../src/server'
let server
beforeEach(() => {
server = makeServer({ environment: 'development' })
})
Run Code Online (Sandbox Code Playgroud)
我还将此块添加到 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]))
})
})
}
})
Run Code Online (Sandbox Code Playgroud)
我将此块添加到 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)
})
})
},
})
}
Run Code Online (Sandbox Code Playgroud)
如果我将 main.js 中的环境“测试”更改为“开发”,则不会产生任何影响。
有什么方法可以查看在服务器运行时的任何时刻哪些路由注册到我的服务器?在我的规范中调试服务器时,服务器的路由属性长度为0。我是否在错误的时间或地点定义了路由?
更新:我发现,当我按照此处所述在 Vue 的 main.js 中创建服务器时,可以在本地 Web 应用程序中使用有效的 Mirage 路由,而不是使用 Cypress 框架。所以现在我认为路由定义没有问题,问题一定出在Cypress请求拦截的代码内部。
我终于在 Mirage 的不和谐频道上的 Sam Selikoff 的帮助下找到了解决方案。我的问题是我的 API 与我的应用程序运行在不同的端口上。
正如 Sam 在 Discord 上所说(我稍微改了一下):
默认情况下
this.passthrough()
仅适用于当前域上的请求。Vue 的 main.js 中快速入门第 4 步的代码需要说明Run Code Online (Sandbox Code Playgroud)this[method]("http://localhost:8090/*", async...
代替
Run Code Online (Sandbox Code Playgroud)this[method]("/*", async...
我希望这对将来的人有帮助。这花了我整整一个星期的时间。