David Faizulaev
David Faizulaev

Reputation: 5761

Jest - stub function within function

I'm writing unit-tests, where I need to set a mock response for a function within a function.

This is the function I want to mock:

cassandraDriver.js

module.exports = ({
  cassandra_user,
  cassandra_password,
  cassandra_address
}) => {
  if (!cassandra_address.length) throw Error('Cassandra address is not valid')
  return new Promise((resolve, reject) => {
    try {
      const client = new driver.Client({
        contactPoints: cassandra_address.split(','),
        authProvider: authProvider(cassandra_user, cassandra_password),
        queryconfig: {
          consistency: driver.types.consistencies.quorum
        }
      })
      return resolve(client)
    } catch (e) {
      reject(e)
    }
  })
}

This is the file that uses it:

const {
  cassandraDriver
} = require('./lib')

    module.exports = async ({
      username = 'cassandra', //default values
      password = 'cassandra', //default values
      address,
      keyspace,
      replication_factor = 1,
      migration_script_path,
      logger = require('bunyan').createLogger({name: 'BuildCassandra'})
} = {}) => {
  try {
       const client = await cassandraDriver(username, password, address)
    }).catch(err => {
      throw Error(err)
    })
  } catch (e) {
    logger.error(e)
    throw e
  }
}

How can I mock the call to 'cassandraDriver' in unit-tests? I tried using rewire, but the method is not exposed as it normally would be. Thanks in advance.

Upvotes: 1

Views: 518

Answers (2)

mpontus
mpontus

Reputation: 2203

You can stub the module which exports cassandraDriver in your test file:

import cassandraDriver from "<path-to-cassandraDriver.js>";

jest.mock("<path-to-cassandraDriver.js>", () => jest.mock());

cassandraDriver.mockImplementation(() => {
  // Stub implementation and return value
});

See Manual Mocks for more information.

Upvotes: 0

ChaseMoskal
ChaseMoskal

Reputation: 7681

let's modify your function so that it can accept a mock driver instead of cassandraDriver

const {
  cassandraDriver
} = require('./lib')

module.exports = async ({
  username = 'cassandra',
  password = 'cassandra',
  address,
  keyspace,
  replication_factor = 1,
  migration_script_path,
  logger = require('bunyan').createLogger({
    name: 'BuildCassandra'
  }),
  driver = cassandraDriver
} = {}) => {
  try {
    const client = await driver(
      username,
      password,
      address
    })
  } catch (e) {
    logger.error(e)
    throw e
  }
}

(i also removed a superfluous .catch block)

next, you should create a "cassandra-driver-mock.js" which emulates the behaviour of the cassandra driver for your unit tests

the unit tests, of course, would pass the mock instead of the real driver as an option parameter

Upvotes: 1

Related Questions