如何在Jest中模拟全局获取

os8fio9y  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(135)
// io_mockglobal.test.js
import {expect, jest} from '@jest/globals';
import {logMovies} from './io';

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ "id": 423638}),
  })
);
beforeEach(() => {
  fetch.mockClear();
});

test("mocks the global values",async()=>{ 
    const l= await logMovies()
    expect(l).toEqual({ "id": 423638});
 })`
// io.js
import path  from 'path';
import { promises as fs } from 'fs';
import fetch from 'node-fetch'

export async function logMovies() {
  const response = await fetch("https://api.github.com/users/hadley/orgs");
  const movies = await response.json();
  return movies[0]
}

控制台:

● mocks the global values

    expect(received).toEqual(expected) // deep equality

    - Expected  -  0
    + Received  + 11

我试图模拟全局获取,但它从logMovies()返回实际值。我如何在Jest中模拟全局获取?

waxmsbnn

waxmsbnn1#

您试图模拟全局fetch,但在您的logMovies中使用了导入的fetch。尝试删除导入,然后它将使用全局fetch

相关问题