简体   繁体   English

如何在 JEST 中测试外部 function 时模拟内部 function

[英]How to mock inner function while testing the outer function in JEST

I am writing an express JS app with TypeScript using functional programming so I don't have any classes and methods in my service.我正在使用函数式编程编写带有 TypeScript 的快速 JS 应用程序,因此我的服务中没有任何类和方法。

I have a method called "getData" in one file:我在一个文件中有一个名为“getData”的方法:

export const getData = async () => {
    const filePath = path.join(__dirname, '../../data/movies.json');
    return MOVIE_METADATA === undefined ? readJsonDataFromFile(filePath) : MOVIE_METADATA;
}

I am using this method in my service in another file like this:我在另一个文件中的服务中使用此方法,如下所示:

const findMovieById = async (movieId: string) => {
    const movies: any[] = await getData();
    return movies.find((movie) => movie.imdbId === movieId || movie.id.toString() === movieId);
}

I want to test my service method "findMovieById" and I want to mock the inner method "getData" to return a mocked response however I am unable to do that.我想测试我的服务方法“findMovieById”,我想模拟内部方法“getData”以返回模拟响应,但我无法做到这一点。

I see a lot of people using SpyOn but that works with a class and then a method but I only have a method.我看到很多人使用 SpyOn,但它适用于 class,然后是一种方法,但我只有一种方法。

I also tried jest-mock-extended npm package but the problem remains the same.我也尝试jest-mock-extended npm package 但问题仍然存在。

I would appreciate it if you could help me here or point be to some resources where I can learn how to mock inner functions while testing outer level functions.如果您能在这里帮助我或指向一些资源,我将在其中学习如何在测试外部函数时模拟内部函数,我将不胜感激。

The test with mocks of getData can be implemented like this:模拟getData的测试可以这样实现:

import * as dataService from "../getDataService";
import { findMovieById } from "../findMovieService";

it("should work with original implementation", async () => {
  const movie = await findMovieById(1);
  expect(movie.title).toEqual("Movie with id 1 from ORIGINAL function");
});

it("should work with mocked implementation", async () => {
  jest
    .spyOn(dataService, "getData")
    .mockResolvedValue([
      { imdbId: 1, title: "Movie with id 1 from MOCKED function" },
    ]);
  const movie = await findMovieById(1);
  expect(movie.title).not.toEqual("Movie with id 1 from ORIGINAL function");
  expect(movie.title).toEqual("Movie with id 1 from MOCKED function");
});

You just need to spyOn the getData function and mock the implementation with mockResolvedValue .您只需要spyOn getData function 并使用mockResolvedValue模拟实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM