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)
})
我是打字稿新手,我正在尝试为 /middleware api 编写测试。我在模拟获取响应时遇到问题。我正在使用 supertest 和 vitest。有人可以帮我吗?
您可以通过在测试文件中编写以下内容来使用
node-fetch
来模拟 vitest
:
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);
这允许您覆盖
node-fetch
的默认导出。
你剩下的是一个模拟的 fetch
函数,它允许你返回任何你想要的东西。
例如,您可以在测试文件中写入以下内容:
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');
...
})
})