0

I'm trying to check that a method was not called again after a certain action.

My test:

 it('if query is less than 3 symbols, api call is not made', () => {
        cy.spy(foo, 'bar').as('bar');

        cy.get('input').type('12').then(() => {
          cy.get('@bar').its('callCount').then(res => {
            expect(res).to.eq(1); // a basic check after mounted hook
          });
        });
      });

My component:

 async mounted(): Promise<void> {
    await this.foo.bar();
  }

 async getSearchResults(): Promise<void> {
    if (this.searchQuery.length < 3) {
      return;
    }
    await this.foo.bar();
  }

The problem is that bar was already called on mount, and it could have been called multiple times before, if query length was valid. I was thinking about saving bar's callCount to a variable and checking it after call, but that looks ugly. Kinda stuck here, any ideas are welcome.

2 Answers2

2

It's not an issue. The call count is started at the point you set up the spy, not when the component is mounted.

Try this:

const foo = {
  bar: () => console.log('bar called')
}

it('starts with a clean callcount', () => {

  foo.bar()                                  // make a call

  cy.spy(foo, 'bar').as('bar');              // callCount === 0 on setup

  cy.get('@bar')
    .its('callCount')
    .should('eq', 0)                         // passes
});

Even if you have some callcount from another test, you can always reset it before the current test:

it('allows reset of spy callCount', () => {

  cy.spy(foo, 'bar').as('bar');               // callCount === 0 on setup

  foo.bar()                                   // make a call, count is now 1

  cy.get('@bar').invoke('resetHistory')       // remove prior calls

  cy.get('@bar')
    .its('callCount')
    .should('eq', 0)                         // passes
});
Fody
  • 23,754
  • 3
  • 20
  • 37
0

I believe you can get the initial call count, and then wrap your test in that.

it('if query is less than 3 symbols, api call is not made', () => {
  cy.spy(foo, 'bar').as('bar');
  cy.get('@bar').its('callCount').then((initRes) => {
    cy.get('input').type('12').then(() => {
      cy.get('@bar').its('callCount').then(res => {
        expect(res).to.eq(initRes); // a basic check after mounted hook
      });
    });
  });
});    

You would probably want to do a test that this would fail, to make sure that Cypress is getting '@bar' again.

agoff
  • 5,818
  • 1
  • 7
  • 20