node.js - Hogyan lehet a node-fetch válaszát szimulálni TypeScript-ben supertest és vitest használatával
import { Router } from 'express'
import fetch from 'node-fetch'
const tasks = Router()
tasks.get('/middleware', async (req,res) => {
const response = await fetch('https://dummy-api')
res.json(response)
})
Újonc vagyok a TypeScript-ben, és teszteket próbálok írni a /middleware API-hoz. Problémákba ütközöm a fetch válaszának mockolásakor. Supertest-et és Vitest-et használok. Tudna valaki segíteni ebben?
Válasz #1
A node-fetch-t a vitest segítségével úgy tudod meghamisítani, hogy a tesztfájlodban a következőt írod:
import * as nodeFetch from "node-fetch";
import { Response } from "node-fetch";
import { vi, describe, it } from "vitest";
import app from '../path-to-your-express-app';
import request from "supertest"
vi.mock("node-fetch", async () => {
const actual: typeof nodeFetch = await vi.importActual("node-fetch");
return {
...actual,
default: vi.fn()
};
});
const fetch = vi.mocked(nodeFetch.default);
Ez lehetővé teszi, hogy felülírja a node-fetch alapértelmezett exportját. Amit kap, az egy mockolt fetch függvény, amely lehetővé teszi, hogy bármit visszaadjon, amit csak szeretne.
Például a következőt írhatja a tesztfájlba:
describe(... () => {
it(... () => {
fetch.mockImplementationOnce(async () =>
new Response('your response body')
)
// now you can send out the request using supertest
// `fetch` won't send a request to `'https://dummy-api'`,
// but instead it will return the response of your `mockImplementationOnce` call
const response = await request(app).get('/middleware');
...
})
})
