question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Not able to test error states with Cypress

See original GitHub issue

I have followed below link to setup miragejs with Cypress.

https://miragejs.com/quickstarts/cypress/setup

Issue: Setup doesn’t work for error responses.

When I add below code in my test.

  /* skipping this test for now becuase miragjs,
   doesn't return error response as expected. */
  server.del('/users/1', () => {
    return new Response(400, {}, { message: 'Invalid input' });
  });

I actually receive below response in my application code (My application is using plain fetch , no axios).

To my surprise response from fetch has status as 200 but has payload as my error response.

{"type":"default","status":200,"ok":true,"statusText":"OK","headers":{"map":{"content-type":"application/json"}},"url":"https://localhost:3030/stores/1","_bodyInit":"{\"message\":\"Invalid input\"}","_bodyText":"{\"message\":\"Invalid input\"}"}

Can someone help me to solve this, I am blocked.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
yugandhar-pathicommented, Jan 16, 2020

@asantos00 Thanks a lot !! for your quick fix. Your fix just works great !!

0reactions
gtsop-pfcommented, Nov 8, 2021

Following up from my previous comment, I managed to get this working by keeping a reference of the Response class on Cypress and using that for my error codes. Here is my code:

cypress/support/index.js
import './commands';

import { setupCypressPassthrough } from '../../src/mirage';

setupCypressPassthrough();
src/mirage/setup-cypress-passthrough.js
import { makeServer } from './make-server';
import { Response } from 'miragejs';

export function setupCypressPassthrough() {
  // https://miragejs.com/quickstarts/cypress/#step-3-have-cypress-define-a-proxy-function-for-your-apps-api-requests
  Cypress.on('window:before:load', (win) => {
    win.handleFromCypress = function (request) {
      return fetch(request.url, {
        method: request.method,
        headers: request.requestHeaders,
        body: request.requestBody,
      }).then((res) => {
        let content = res.headers.get('content-type').includes('application/json')
          ? res.json()
          : res.text();
        return new Promise((resolve) => {
          content.then((body) => resolve([res.status, res.headers, body]));
        });
      });
    };
  });

  // https://miragejs.com/quickstarts/cypress/#step-5-write-tests-using-your-mirage-server
  let server;

  beforeEach(function () {
    server = makeServer({
      environment: 'development',
    });

    // provide server instance via `this.server` to test cases (`it` blocks)
    cy.wrap(server).as('server');

    cy.wrap(Response).as('Response');
  });

  afterEach(() => {
    server.shutdown();
  });
}
cypress/integration/home.spec.js
describe('Pages | Home', function () {
  it("Shows an error message when shops won't load", function () {
    cy.visit('/');

    this.server.get('/api/user/stores', () => {
      return new this.Response(401, {}, { error: 'fail' });
    });
  });
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Error Messages | Cypress Documentation
This message means that Cypress was unable to find tests in the specified file. You'll likely get this message if you have an...
Read more >
Cypress : how can I fail a test if an error occurs but only at the ...
I have already seen these answers ==> Cypress: Is it possible to complete a test after failure, Denial of Service (status code 429)...
Read more >
Cypress and Flaky Tests: How to Handle Timeout Errors
Asynchronous operations are not completing before Cypress runs a command, causing a timeout error. Flaky Cypress Tests Caused by Timeout Errors.
Read more >
How to handle Errors in Cypress | BrowserStack
An Exception or an Error is an abnormal event, which may break the normal flow of test script execution, in turn causing the...
Read more >
Fixing Cypress cross-origin errors - Reflect.run
The reason why Cypress historically has not been able to test across domains is because since it operates inside the browser runtime, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found