Compatibility between cypress and react-apollo

人走茶凉 提交于 2021-02-10 14:22:59

问题


I am using react-apollo to make GraphQL queries, and I am using Cypress for testing.

The problem is that these 2 dont seem to play well along. Apollo seems to be making all its requests through the Fetch API.

But Cypress seems like it is not able to capture anything, except XHR requests.

So what could I do to solve this problem? Is there a way for Cypress to capture "fetch" requests? Is there a way for react-apollo to use "xhr" instead of "fetch"?


回答1:


Try out cypress-graphql-mock

You just pass it your schema:

const schema = fs.readFileSync('../../app-schema.graphql', 'utf8');
// alternatively, using a dumped introspection query:
// const schema = require('../../dumped-schema.json')

beforeEach(() => {
  cy.server();
  cy.mockGraphql({ schema });
});



回答2:


An easy workaround is to use whatwg-fetch, which you'd add as a dependency via npm and then...

cypress/support/fetch_to_xhr.js

function fetchToXhr() {
  let polyfill

  before(() => {
    cy.readFile('node_modules/whatwg-fetch/dist/fetch.umd.js')
      .then((contents) => polyfill = contents)
    Cypress.on('window:before:load', (win) => {
      delete win.fetch
      win.eval(polyfill)
    })
  })
}

fetchToXhr()

cypress/support/index.js

import "./fetch_to_xhr";

After that cypress will capture the graphql requests



来源:https://stackoverflow.com/questions/56890766/compatibility-between-cypress-and-react-apollo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!