cypress-io/cypress-react-unit-test

can not mock fetch by cy.route

github-hanchao opened this issue · 2 comments

image

https://github.com/bahmutov/cypress-react-unit-test/blob/ff4bdcc98e63626e4ffe532d58f20eeadcf6ef4b/cypress/component/basic/network/2-users-fetch.jsx

https://github.com/bahmutov/cypress-react-unit-test/blob/ff4bdcc98e63626e4ffe532d58f20eeadcf6ef4b/cypress/component/basic/network/2-users-fetch-spec.js#L33

import React from 'react'
import { mount } from 'cypress-react-unit-test'

export class Users extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      users: [],
    }
  }

  componentDidMount() {
    fetch('https://jsonplaceholder.cypress.io/users?_limit=3')
      .then(response => {
        return response.json()
      })
      .then(list => {
        this.setState({
          users: list,
        })
      })
  }

  render() {
    return (
      <div>
        {this.state.users.map(user => (
          <li key={user.id}>
            <strong>{user.id}</strong> - {user.name}
          </li>
        ))}
      </div>
    )
  }
}


describe('Users with Fetch', () => {
  // https://github.com/bahmutov/cypress-react-unit-test/issues/347
  
    beforeEach(() => {
      cy.server()
      // mount the component after defining routes in tests
      // preventing race conditions where you wait on untouched routes
    })

    it('can stub and display mock network response', () => {
      const users = [{ id: 1, name: 'foo' }]
      // stub the request
      cy.route('GET', '/users?_limit=3', users).as('users')
      mount(<Users />)
      cy.get('li')
        .should('have.length', 1)
        .first()
        .contains('foo')
    })
  
})

BTW the axios.get works
https://github.com/bahmutov/cypress-react-unit-test/blob/ff4bdcc98e63626e4ffe532d58f20eeadcf6ef4b/cypress/component/basic/network/1-users.jsx

 componentDidMount() {
    axios
      .get('https://jsonplaceholder.cypress.io/users?_limit=3')
      .then(response => {
        // JSON responses are automatically parsed.
        this.setState({
          users: response.data,
        })
      })
  }

Make sure "experimentalFetchPolyfill": true is present in your cypress.json for https://www.cypress.io/blog/2020/06/29/experimental-fetch-polyfill/

Screen Shot 2020-08-26 at 10 45 28 AM