typescriptunit-testingmockingjestjs

How can you mock imported functions in TypeScript using Jest?


I am having a module called map-creation.service.ts:

export const createMap = (asyncJobId: string, resourceUrl: string, s3DestFolder: string) => {

};

Which is used in my endpoint:

import {createMap} from './services/map-creation.service';

const router = express.Router();
const routePrefix = config.get('server.routePrefix');

router.post(`/${routePrefix}`, validate(validation), (req: express.Request, res: express.Response) => {
    createMap(req.body.asyncJobId, req.body.resourceUrl, req.body.s3DestFolder);
    res.status(201).json({message: 'Created'});
});

When I am trying to mock this module in my tests, and want to test if it was called when requesting the endpoint, I still get: Expected mock function to have been called with: ... But it was not called.

jest.mock('../../../src/services/map-creation.service');
import {createMap} from '../../../src/services/map-creation.service';

And here's my test:

it('should call the map-creation service', () => {
        return request(server)
            .post(`/${routePrefix}`)
            .send({
                asyncJobId,
                resourceUrl,
                s3DestFolder
            })
            .then(res => {
                expect(createMap).toBeCalledWith(asyncJobId, resourceUrl, s3DestFolder);
            });
    });

If I am mocking the method like this:

import {createMap} from '../../../src/services/map-creation.service';
createMap = jest.fn();

The test passes, but tslint is complaining: Cannot assign to 'createMap' because it is not a variable. So what would be the proper way to mock this method in TypeScript and Jest?


Solution

  • So what would be the proper way to mock this method in TypeScript and Jest?

    Use dependency injection to inject the mock vs. real version of functions as needed.

    Recommended framework for DI: http://inversify.io/

    but tslint is complaining: Cannot assign to 'createMap' because it is not a variable

    Please don't do this. Imports should be considered immutable. You will get a compile time TypeScript error for this as well and when module support becomes native you will get a runtime error.