Integrating with other tools

mockit exposes APIs to modify its internal state. You can use this to your benefit.

Integrating with Cypress.io

When it comes to browser testing, you will often find yourself needing to stub out different responses to bring your UI to a different state. With mockit, this makes it very easy.

This is an example with how you can do it using Cypress.io. The process would be very similar given any other tools.

commands.js
Cypress.Commands.add('resetMockit', () => {
    const defaultLog = {
        displayName: 'RESET SERVER STATE',
    };
    
    // Makes request to mockit to reset server state
    return fetch('http://localhost:3000/mockit/api/reset', {
        method: 'PUT',
    }).then(() => {
        return Cypress.log({
            ...defaultLog,
        });
    }).catch(err => {
        return Cypress.log({
            ...defaultLog,
            message: err,
        });
    });
});

Cypress.Commands.add('switchContract', id => {
    const defaultLog = {
        displayName: 'SWITCH CONTRACT',
    };
    
    // Makes request to mockit to update active fixture
    return fetch('http://localhost:3000/mockit/api', {
        method: 'PUT',
        body: JSON.stringify({ id }),
        headers: {
            'Content-Type': 'application/json',
        },
    }).then(() => {
        return Cypress.log({
            ...defaultLog,
            message: `Switched to ${id}`,
        });
    }).catch(() => {
        return Cypress.log({
            ...defaultLog,
            message: 'Failed to switch',
        });
    });
});

With these commands now loaded into Cypress, you can use them in your tests.

test.spec.js
describe('Integrating mockit with Cypress', () => {
      beforeEach(() => {
            cy.resetMockit();
      });
      
      it('should login', () => {
            cy
                  .visit('my-site')
                  .login()
                  .should('contain', 'Welcome');
      });
      
      it('should not login', () => {
            cy
                  .switchContract('FAILED_LOGIN')
                  .visit('my-site')
                  .login()
                  .should('contain', 'Failed to login');
      });
});

Last updated