esbuild-runner icon indicating copy to clipboard operation
esbuild-runner copied to clipboard

`jest.mock()` calls not getting hoisted to the top by `esbuild-runner/jest`

Open joquijada opened this issue 3 years ago • 3 comments

I created an issue/question for this in SST at https://github.com/serverless-stack/serverless-stack/issues/1065. I'm wondering if I'm doing something wrong or if this just a shortcoming of esbuild-runner. How come the jest.mock() calls are not hoisted to the top in the generated JavaScript files of Jest tests written in TypeScript? Below is snippet of the resulting JavaScript, notice the jest.mock() calls appear towards the middle, nowhere near the top as Jest babel-jest transformer for example would do,

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const lambda = __importStar(require("../src/acme-lambda"));
jest.mock('ioredis');
jest.mock('@acme/common-util');
...

joquijada avatar Nov 18 '21 23:11 joquijada

+1

jonyw4 avatar Dec 28 '21 18:12 jonyw4

Can confirm, using esbuild-runner with tests that need to jest.mock imported functions will break things. If you want to quickly reproduce this problem you can setup any test that required mocking imported functions

// something.test.ts

import { importedFunction } from './otherFile'

jest.mock('./otherFile', () => ({
  importedFunction: jest.fn().mockResolvedValue(true),
}))

ulissesferreira avatar May 10 '23 09:05 ulissesferreira

any solution for this?

I replaced @swc/jest transformer with esbuild-runner/jest and jest.mock no longer works correctly

some.test.ts

import { myModule } from "@/someDir";
import { myFunction } from "@/myFunction";

jest.mock("@/someDir")

test("test1", () => {
  (myModule as Jest.MockedFunction).mockImplementationOnce(() => Promise.resolve(true));

  myFunction();
  
  expect(myModule).toHaveBeenCalledTimes(1)
 
});

@/myFunction.ts

import { myModule } from "@/someDir";

export function myFunction() {
  // other code...
  myModule();
}

qaynam avatar Feb 26 '24 06:02 qaynam