Replies: 1 comment 7 replies
-
I've spent a lot of time doing TDD with mocks in Vitest (and Jest before it, and
This doesn't look quite right to me. Because of import { axiosClient } from "../axiosClient";
import * as subject from "../subject";
vi.mock("../axiosClient");
describe("api", () => {
it("should call GET /foo", async () => {
vi.mocked(axiosClient.get).mockResolvedValue({ data: { mockData: true } });
const result = await subject.fetchFoo();
expect(axiosClient.get).toHaveBeenCalledWith("/foo");
expect(result).toEqual({ mockData: true });
});
});
While I dislike the magic of hoisting, I think mixing and matching mocks vs real modules in a single test suite leads to confusion. In that way, I find
I've found it to be the other way around;
You can use the import { describe, expect, it, vi } from "vitest";
import { when } from "vitest-when";
import { axiosClient } from "../axiosClient";
import * as subject from "../subject";
vi.mock("../axiosClient");
describe("fetching foo", () => {
afterEach(() => {
vi.resetAllMocks()
})
it("should call GET /foo", async () => {
when(axiosClient.get)
.calledWith("/foo")
.thenResolve({ data: { mockData: true } });
const result = await subject.fetchFoo();
expect(result).toEqual({ mockData: true });
});
});
True! I only ever experience this as an occasional minor inconvenience that I fix with a find-and-replace, so I don't personally consider it that important. Might be an interesting feature for the VSCode extension, though!
I've found |
Beta Was this translation helpful? Give feedback.
-
What is the best practice for mocking?
It seems that these are equivalent. What are the benefits of using each approach?
vi.spyOn
can be called from anywhere (even at the top afterimports
)vi.mock
is way more verbose for the same functionality asvi.spyOn
.vi.spyOn
is more type safe (notice invi.mock
get
, I can return anythingvi.mock
requires all functions mocked, so casting tounknown
is a workaroundvi.spyOn
is more explicit/strict with async/await (noticemockResolvedValue
rather thanmockReturnValue
)vi.mock
doesn't work well if you re-name/move files ("../axiosClient" would not auto-refactor etc)vi.spyOn
is more feature rich (mocking implementations, mocking variables etc)It seems to me that
vi.spyOn
is superior? What does everyone think?Beta Was this translation helpful? Give feedback.
All reactions