Mocking meteor package imports in Jest?

In case others find this question, here is a link to a helpful issue that @ffxsam raised on the jest repo-- https://github.com/facebook/jest/issues/1388. Long story short, use the moduleNameMapper property in your jest config, and it “just works” :slight_smile: Here’s an example config:

// jest-config.json
{
  "collectCoverage": true,
  "coverageDirectory": "tests/jest-coverage",
  "moduleNameMapper": {
    "^meteor/kadira:flow-router$": "<rootDir>/tests/jest-meteor-stubs/FlowRouter.js"
  },
  "resetMocks": true,
  "testRegex": "((tests\/jest/.*|\\.(test|spec))\\.(js|jsx)$)",
  "verbose": true
}

a function that uses FlowRouter:

// imports/startup/client/globalUIHelpers/cjfPathFor.js

import { FlowRouter } from 'meteor/kadira:flow-router';

export default function cjfPathFor(routeName) {
  return FlowRouter.path(routeName);
}

the test…

// tests/jest/ui-helpers/cjfPathFor-test.js

/* eslint-env jest */
/* eslint-disable no-console, global-require, import/first */
import { FlowRouter } from 'meteor/kadira:flow-router';
import cjfPathFor from '../../../imports/startup/client/globalUIHelpers/cjfPathFor';

describe('cjfPathFor', () => {
  it('calls FlowRouter.path', () => {
    const testPath = 'Signup';
    cjfPathFor(testPath);
    expect(FlowRouter.path).toBeCalledWith(testPath);
  });
});

and the stub…

// tests/jest-meteor-stubs/FlowRouter.js

/* eslint-env jest */
module.exports = {
  FlowRouter: {
    path: jest.fn(),
  },
};

1 Like