folke / esbuild-runner

⚡️ Super-fast on-the-fly transpilation of modern JS, TypeScript and JSX using esbuild
https://www.npmjs.com/package/esbuild-runner
Apache License 2.0
711 stars 24 forks source link

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

Open joquijada opened 2 years ago

joquijada commented 2 years ago

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');
...
jonyw4 commented 2 years ago

+1

ulissesferreira commented 1 year ago

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),
}))
qaynam commented 6 months ago

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();
}