运行e2e测试时在cypress中模拟特定的graphql请求 [英] Mock specific graphql request in cypress when running e2e tests

查看:243
本文介绍了运行e2e测试时在cypress中模拟特定的graphql请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Cypress 运行e2e测试时,我的目标是模拟特定的graphql查询。

When running e2e tests with Cypress, my goal is to mock a specific graphql query.

当前,我可以模拟所有这样的请求:

Currently, I can mock all requests like this:

cy.server();
cy.route('POST', '/graphql', {
    data: {
        foo: 'bar'
    },
});

问题是,这会模拟 all / graphql 查询。如果我能以某种方式说:

The problem is that this mocks all /graphql queries. It would be awesome if I somehow could say:

cy.route('POST', '/graphql', 'fooQuery', {
    data: {
        foo: 'bar'
    },
});

在我们的应用程序中,我们使用的是Apollo Graphql-因此所有查询都被命名。

In our application, we are using Apollo Graphql - and thus all queries are named.

推荐答案

使用赛普拉斯5.1,使用新的 route2 命令,模拟Gr​​aphQL非常简单请求,例如:

With cypress 5.1, using the new route2 command it is very simple to mock GraphQL requests, for example:

cy.route2('/graphql', (req) => {
  if(req.body.includes('operationName')){
    req.reply({ fixture: 'mockData.json'});
  }
});

我刚刚添加了一个if条件,以评估GraphQL请求的正文是否包含某些字符串作为查询的一部分。
如果是这样,那么我会从固定装置中加载自定义主体进行回复。

I just added an if condition to evaluate if the body of the GraphQL request contains certain string as part of the query. If that is true, then I reply back with a custom body loaded from a fixture.

cy.route2()
https://docs.cypress.io/api/命令/route2.html

这篇关于运行e2e测试时在cypress中模拟特定的graphql请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆