How to stub a GET network request
// Approach 1 - Data is colocated with code
describe('application initialisation', () => {
it('displays the correct number of items in the todo list', () => {
cy.server()
cy.route('GET', '/api/todos', [
{ id: 1, name: 'Eat', isComplete: true },
{ id: 2, name: 'Sleep', isComplete: false },
{ id: 3, name: 'Dream', isComplete: false },
])
cy.visit('/')
cy.get('.list-item').should('have.length', 3)
})
})
// Approach 2 - Data is separated from code
// Store data in ./fixtures/todos.json
[
{ "id": 1, "name": "Eat", isComplete: true },
{ "id": 2, "name": "Sleep", isComplete: false },
{ "id": 3, "name": "Dream", isComplete: false }
]
// Use fixture data in test file
describe('application initialisation', () => {
it('displays the correct number of items in the todo list', () => {
cy.server()
cy.fixture('todos')
.then((todos) => {
cy.route('GET', '/api/todos', todos)
})
cy.visit('/')
cy.get('.list-item').should('have.length', 3)
})
})
// Approach 3 - More Concise Form Of Approach 2
// Store data in ./fixtures/todos.json
[
{ "id": 1, "name": "Eat", isComplete: true },
{ "id": 2, "name": "Sleep", isComplete: false },
{ "id": 3, "name": "Dream", isComplete: false }
]
// Use fixture data in test file
describe('application initialisation', () => {
it('displays the correct number of items in the todo list', () => {
cy.server()
cy.route('GET', '/api/todos', 'fixture:todos')
cy.visit('/')
cy.get('.list-item').should('have.length', 3)
})
})
Last updated
Was this helpful?