【问题标题】:How to stub a call to graphql using cypress?如何使用 cypress 存根对 graphql 的调用?
【发布时间】:2018-03-02 23:37:50
【问题描述】:

我正在编写一个使用 vue-apollo 与 graphql 交互的 Vue 应用程序。我想知道是否可以存根 graphql 请求。我认为这应该可行:

  it('should access a story', function() {
    cy.server();
    cy.route('http://localhost:3002/graphql', {
      data: {
        Story: { id: 2, title: 'story title', content: 'story content' }
      }
    });

    cy.visit('/stories/2');
  });

不幸的是,我从 graphql 收到一个错误,抱怨 idInt 而不是 ObjectId。我错过了什么吗?

【问题讨论】:

    标签: graphql cypress


    【解决方案1】:

    问题在于,在 Cypress 中尚未实现存根 fetch 请求(这是 Vue Apollo 正在使用的)。我最终遵循了these 的说明:

    • 安装github/fetch
    • 将此添加到cypress/support/index.js:

    .

    Cypress.on('window:before:load', win => {
      win.fetch = null;
      win.Blob = null;
    });
    

    现在可以了!

    【讨论】:

      【解决方案2】:

      我在这里使用这个包:

      1. npm i @iam4x/cypress-graphql-mock

      2. 将此行添加到 'support/commands.js'

      import "@iam4x/cypress-graphql-mock";

      1. 转到您的 graphiql 游乐场并下载您的架构

      2. 将任务命令添加到“plugins/index.js”(记得更改您之前下载的架构文件的路径)

      module.exports = (on, config) => {
        on("task", {
          getSchema() {
            return fs.readFileSync(
              path.resolve(__dirname, "../../../schema.graphql"),
              "utf8"
            );
          }
        });
      };
      
      1. 使用加载的架构编写测试
      beforeEach(() => {
        cy.server();
        cy.task("getSchema").then(schema => {
          cy.mockGraphql({
            schema
          });
        });
      });`
      
      describe("Login Form", () => {
        it("should redirect after login", () => {
          cy.mockGraphqlOps({
            operations: {
              Login: {
                login: {
                  jwt: "some-token",
                  user: {
                    id: "5d5a8e1e635a8b6694dd7cb0"
                  }
                }
              }
            }
          });
          cy.visit("/login");
          cy.getTestEl("email-input").type("Max Mustermann");
          cy.getTestEl("password-input").type("passwort");
          cy.getTestEl("submit").click();
          cy.getTestEl("toolbar-title").should("exist");
        });
      })
      
      1. 访问原始存储库以获得进一步的解释,因为我发现它不那么令人困惑。您安装的软件包只是这个软件包的一个工作分支: https://github.com/tgriesser/cypress-graphql-mock

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        • 2020-06-17
        • 2020-04-16
        • 1970-01-01
        • 2020-12-03
        • 2021-05-11
        相关资源
        最近更新 更多