Baranidharan S
Baranidharan S

Reputation: 135

Mock require/import modules using cypress

I'm using sequelize with graphql to connect my postgresql in my react nodejs project. And I'm using Cypress for unit testing. While doing that, I got stuck on how to mock the module import.

describe('db config using sequelize', { tags: ['@unit'] }, () => {
  before(() => {
    const SequelizeStub = {
      authenticate: new Cypress.Promise((resolve) => { resolve(true) }),
      DataTypes: cy.stub().returns({}),
    }
    cy.stub('sequelize').returns(SequelizeStub)
  })

  it('db config authenticate', async () => {
    const { connect } = require('@db/common/dbconfig')
    assert.isBoolean(connect.authenticate())
  })
})

The @db/common/dbconfig file calls the require('sequelize') and creating the object for sequelize and using the Sequelize object I'm connecting to Postgresql.

So while writing the unit test case coverage for dbconfig file, I would like to mock the require('sequelize') itself instead of the module gets loaded for testing.

So I wrote a stub and replacing it with 'sequelize' assuming that it will mock. But not sure this is the right approach. While running it, I'm getting the following error.

TypeError: Cannot read properties of undefined (reading 'value')

Because this error occurred during a before all hook we are skipping the remaining tests in the current suite: db config using sequelize

Although you have test retries enabled, we do not retry tests when before all or after all hooks fail

Can someone help me with this stub mocking?

Upvotes: 0

Views: 1829

Answers (1)

Baranidharan S
Baranidharan S

Reputation: 135

Learnt that without importing the actual model, it is not possible to mock it.

So I updated the code as follows,

  const SEQUELIZE_NAMESPACE = {
    Sequelize: require('sequelize'),
  }

  const mSequalize = {
    authenticate: cy.stub().callsFake(
      (params, callback) => {
        return new Cypress.Promise((resolve) => resolve())
      }),
    define: cy.stub().callsFake(
      (params, callback) => {
        return {}
      }),
  }
  cy.stub(SEQUELIZE_NAMESPACE, 'Sequelize').callsFake((params, callback) => mSequalize)

Used the same const SEQUELIZE_NAMESPACE in source file as well as follows,

  const SEQUELIZE_NAMESPACE = {
    Sequelize: require('sequelize'),
  }

And then created object as follows,

const sequelize = new SEQUELIZE_NAMESPACE.Sequelize(...)

and then it worked. Thanks for one of my peer (@rsmuthu) who helped me fix this.

Upvotes: 0

Related Questions