node.js - როგორ შევქმნათ node-fetch-ის პასუხის მოდელი TypeScript-ში, გამოყენებით supertest და vitest


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-სთვის. მე შევხვდი სირთულეებს fetch პასუხის მოკინგში. მე ვიყენებ supertest-ს და vitest-ს. შეუძლია ვინმეს დამეხმაროს ამის გაკეთებაში?

პასუხი #1

შეგიძლიათ გააკეთოთ 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');

    ...
  })
})