Cypress test not failing from exception in mocked object

Viewed 288

My test contains something like this:

it.only('does something', function() {
    cy.window().then(function(win) {
      win.GlobalObject = {
        someMethod: function(data) {
          return expect(data).to.deep.eq({
            company: 'Pied Piperz',
            country: 'United States'
          });
        }
      };
    });
    cy.get('[data-cy=submit]').click();
});

When my test runs, part of the logic invokes window.GlobalObject.someMethod({}) which should fail the test since I didn't pass the expected object into someMethod(). Instead, I see a failing assertion in the log:

But the overall test is marked as succeeding:

How can I get get the failing asserting inside my mocked GlobalObject to fail the whole test?

1 Answers

The problem is that your test is failing AFTER it has already passed.

Once Cypress finishes cy.get('[data-cy=submit]').click(), it's done executing all the commands, so it considers your test to have completed.

Then, some milliseconds later, you have a failing expect() - but Cypress has already passed the test, so there is nothing meaningful to be done.

But all is not lost! You can use the optional done parameter to manually tell Cypress when the test has finished, like so:

it.only('does something', function(done) { // <--- note `done` here
    cy.window().then(function(win) {
      win.GlobalObject = {
        someMethod: function(data) {
          expect(data).to.deep.eq({
            company: 'Pied Piperz',
            country: 'United States'
          });
          done(); // <--- this call tells Cypress the test is over
        }
      };
    });
    cy.get('[data-cy=submit]').click();
});
Related