How to mock node-fetch with Vitest
Akira Kashihara
Posted on April 17, 2022
What I Want to Do
I want to mock node-fetch with Vitest, which is a unit-test framework. Jest introduces how to make a node-fetch mock.
Vitest is compatible with Jest in large part, but Vitest does not provide jest.requireActual
helper is used in the above-linked article.
This article introduces how to mock node-fetch
without using jest.requireActual
by using Vitest.
Required Environment
- Node.js
Adding Necessary Dependencies
Vitest has not been common yet (at least in Japan), so I indicate how to install necessary dependencies.
npm i -D vitest vi-fetch node-fetch
The Function I test
I made a simple function for testing. This function returns the count
value of JSON on the response to access https://hogehoge.hogehoge.hogehoge with the GET method.
import fetch from "node-fetch";
export const getCountNode = async () => {
const response = await fetch("https://hogehoge.hogehoge.hogehoge"); // GET
const countJson = await response.json(); // Get response body as json
return countJson.count; // Return the value of count key in the response
};
Writing Testing Code
As I mentioned before, Vitest does not provide jest.requireActual
helper, so I implemented the following source code in reference to the answer written by E. Coleman et al. on stack overflow.
import { describe, it, expect, vi } from "vitest";
import fetch from "node-fetch";
import { getCountNode } from "./getCountNode";
describe("sample", () => {
it("hello", async () => {
vi.mock("node-fetch");
fetch.mockReturnValue(
Promise.resolve({ json: () => Promise.resolve({ count: 33 }) })
);
const result = await getCountNode();
expect(result).toBe(33);
});
});
Testing
The result of this testing is shown in the following. This result indicates "2 passed" because I ran another test simultaneously.
Failed Testing Result
I modified the expected value in the testing. This testing failed.
import { describe, it, expect, vi } from "vitest";
import fetch from "node-fetch";
import { getCountNode } from "./getCountNode";
describe("sample", () => {
it("hello", async () => {
vi.mock("node-fetch");
fetch.mockReturnValue(
Promise.resolve({ json: () => Promise.resolve({ count: 33 }) })
);
const result = await getCountNode();
expect(result).toBe(31);
});
});
This result is the following.
Annotation
This article is originally written in Japanese.
Posted on April 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.