trivikr / vitest-codemod

Codemod scripts to migrate your JavaScript unit tests to vitest
MIT License
23 stars 2 forks source link

[Feature]: Support transformation of default exports #107

Closed trivikr closed 1 year ago

trivikr commented 1 year ago

Self-service

Problem

In vitest, the default exports need to be mocked as default

Example test code:

import getDefault from "./getDefault";

jest.mock("./getDefault", () => "mockFromDefault");

test("mockDefault", () => {
  expect(getDefault()).toBe("mockFromDefault");
});

Solution

The transformed code in vitest should be:

import getDefault from "./getDefault";

vi.mock("./getDefault", () => ({ default: () => "mockFromDefault" }));

test("mockDefault", () => {
  expect(getDefault()).toBe("mockFromDefault");
});

Alternatives

N/A

Additional context

No response

trivikr commented 1 year ago

This is a complex test case in Jest.

Adding wontfix as of now. This can be revisited in a new issue, if someone files a production use case in future.

trivikr commented 1 year ago

Reopening, as I came across a test case which can be used for testing in workspace setup.

Input code:

jest.mock("./defaultExport", () => "defaultFromMock");

test("mockDefault", async () => {
  const { default: defaultExport } = await import("./defaultExport");
  expect(defaultExport).toBe("defaultFromMock");
});

Expected transform code:

import { expect, test, vi } from "vitest";
vi.mock("./defaultExport", () => ({ default: "defaultFromMock" }));

test("mockDefault", async () => {
  const { default: defaultExport } = await import("./defaultExport");
  expect(defaultExport).toBe("defaultFromMock");
});

Code being tested:

// defaultExport.js is a module that exports a default value.
module.exports = "default";
github-actions[bot] commented 1 year ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs and link to relevant comments in this thread.