无法使用cypressJS请求路线

时间:2019-05-06 09:16:24

标签: 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中的示例,但我不知道为什么这是错误的。我知道,那棵柏树只能处理XMLHttpRequests,所以我为axios配置了它,我想用acios模拟通常在我的SPA中发生的呼叫。

1 个答案:

答案 0 :(得分: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存储库,我将为您提供帮助

相关问题