【问题标题】:Can't request route with cypressJS无法使用 cypressJS 请求路由
【发布时间】:2019-05-07 13:41:27
【问题描述】:

我尝试简单地从 cypress 测试中的路由请求数据:

it("Then it works", () => {

    cy.server()           
    cy.route({
        method: 'GET',     
        url: '/users/1',    
        response: true      
    })
    axios.defaults.headers.common = {
        "X-Requested-With": "XMLHttpRequest"
    }

    axios.get("http://localhost:8080/users/1").then(response => {
        console.log(response)
        expect(response.body).to.equal(true)
    }).catch(error => console.log(error))
})

我得到的只是“错误:请求失败,状态码为 404”,因此该路由似乎不适用于 axios。在我的 cypress.json 中,我将基本 URL 配置为:

{
  "baseUrl": "http://localhost:8080"
}

从我的角度来看,它基本上是来自documentation 的示例,我无法弄清楚为什么它是错误的。我知道,cypress 只能处理 XMLHttpRequests,所以我为 axios 配置了这个,我想用 acios 模拟一个通常发生在我的 SPA 中的调用。

【问题讨论】:

    标签: cypress


    【解决方案1】:

    您在测试内部进行调用,而cy.route 有助于拦截前端请求。更多:记住(来自赛普拉斯文档)

    Cypress 命令被排队并异步运行

    我的意思是:必须调用axios.get的是前端应用程序,而不是你直接从测试中调用。

    你可以这样做:

    • cy.visit 全局定义了 axios 的页面
    • 让调用从前端开始
    it("Then it works", () => {
    
        cy.server()           
        cy.route({
            method: 'GET',     
            url: '/users/1',    
            response: true      
        })
        cy.visit("http://localhost:8000"); // replace it with your working app
        cy.window().then(win => {
            axios.defaults.headers.common = {
                "X-Requested-With": "XMLHttpRequest"
            }
    
            axios.get("http://localhost:8080/users/1").then(response => {
                console.log(response)
                expect(response.body).to.equal(true)
            }).catch(error => console.log(error))
        })
    })
    

    一切都应该正常。如果没有,请与它分享一个 GitHub 存储库,我会帮你的?

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多