Sinon: Stubbing default exported functions

Created on 16 Nov 2017  路  2Comments  路  Source: sinonjs/sinon

It is a common use case to mock ES modules.

e.g. I have a module that imports getEventByEventId

import getEventByEventId from '../queries/getEventByEventId';

export default async (
  {
    connection,
    session
  }: ResolverContextType
) => {
  if (!session || !session.userId) {
    throw new Error('User must be authenticated.');
  }

  const event = await getEventByEventId(connection, eventId);

  // ..
}

In my test I want to mock getEventByEventId, e.g.

import test from 'ava';
import sinon from 'sinon';
import moment from 'moment';
import createReservation from '../../../src/mutators/createReservation';

test('throws an error if the event is in the past', async (t) => {
  const parameters: any = {};

  const context: any = {
    session: {
      userId: 1
    }
  };

  const stub = sinon.stub().returns({
    date: moment().format('YYYY-MM-DD'),
    time: moment(new Date().getTime() - 1000 * 60).format('HH:mm')
  });

  // How to use the stub to mock `getEventByEventId`?

  await t.throws(createReservation(context), 'Cannot create a reservation for a past event.');
});

This was asked before here: https://github.com/sinonjs/sinon/issues/1358 . But this got unrightly closed as a duplicate of: https://github.com/sinonjs/sinon/issues/1121 , while it is a totally different issue.
This was already mentioned in that issue, but it doesn't seem to get looked after anymore.

ES2015+

All 2 comments

Sinon.JS does not concern itself with module systems. I am closing this.

Because of the many requests that keep coming in, and that the stewards of the project also write tests for a living, we have published How To Use Link Seams With CommonJS.

Please help us keep the issues list manageable and ask usage questions on the Sinon.JS users mailinglist or StackOverflow. Both are good resources where the wider audience of users can offer help.

@sebakerckhof checkout this https://github.com/sinonjs/sinon/issues/562#issuecomment-399090111

Was this page helpful?
0 / 5 - 0 ratings