nachocab
nachocab

Reputation: 14364

How to stub a call to graphql using cypress?

I'm writing a Vue app that uses vue-apollo to interact with graphql. I'm wondering if it's possible to stub the graphql requests. I thought this should work:

  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');
  });

Unfortunately, I get an error from graphql complaining that id is an Int instead of an ObjectId. Am I missing something?

Upvotes: 3

Views: 2962

Answers (2)

Sebastian Jung
Sebastian Jung

Reputation: 97

I got it working with this package here:

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

  2. Add this line to 'support/commands.js'

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

  1. go to your graphiql playground and download your schema enter image description here

  2. add task command to 'plugins/index.js' (REMEMBER TO CHANGE PATH TO SCHEMA FILE YOU DOWNLOADED EARLIER)

module.exports = (on, config) => {
  on("task", {
    getSchema() {
      return fs.readFileSync(
        path.resolve(__dirname, "../../../schema.graphql"),
        "utf8"
      );
    }
  });
};
  1. write your tests with loaded schema
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. Visit the original repo for further explanation as i find it less confusing. The package you have installed is just a working fork of this one: https://github.com/tgriesser/cypress-graphql-mock

Upvotes: 0

nachocab
nachocab

Reputation: 14364

The problem was that stubbing fetch requests isn't yet implemented in Cypress (which is what Vue Apollo is using). I ended up following these instructions:

  • Install github/fetch
  • Add this to cypress/support/index.js:

.

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

Now it works!

Upvotes: 5

Related Questions