5

我在 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 路由,而不是使用赛普拉斯框架。所以现在我认为路由定义很好,问题一定在赛普拉斯请求拦截的代码中。

4

1 回答 1

4

在 Mirage 的不和谐频道上,我终于在 Sam Selikoff 的帮助下找到了解决方案。我的问题是我的 API 运行在与我的应用程序不同的端口上。

正如 Sam 在 discord 上所说的(我稍微改述了一下):

默认情况下this.passthrough()仅适用于当前域上的请求。Vue 的 main.js 中快速入门第 4 步的代码需要说明

this[method]("http://localhost:8090/*", async...

代替

this[method]("/*", async...

我希望这对将来的某人有所帮助。我花了整整一周的时间。

于 2020-04-10T12:21:20.550 回答