我正在使用函数式编程用TypeScript编写一个快捷JS应用程序,所以我的服务中没有任何类和方法。
我在一个文件中有一个名为"getData“的方法:
export const getData = async () => {
const filePath = path.join(__dirname, '../../data/movies.json');
return MOVIE_METADATA === undefined ? readJsonDataFromFile(filePath) : MOVIE_METADATA;
}我在另一个文件中使用此方法服务,如下所示:
const findMovieById = async (movieId: string) => {
const movies: any[] = await getData();
return movies.find((movie) => movie.imdbId === movieId || movie.id.toString() === movieId);
}我想测试我的服务方法"findMovieById“,并且我想模拟内部方法"getData”来返回一个模拟的响应,但是我无法这样做。
我看到很多人使用SpyOn,但这适用于一个类,然后是一个方法,但我只有一个方法。
我也尝试了jest-mock-extended npm包,但问题仍然是一样的。
如果您能在这里帮助我,或者指向一些资源,我将非常感激,在这些资源中,我可以学习如何在测试外部级函数的同时模拟内部函数。
发布于 2022-09-30 23:10:38
使用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");
});您只需要spyOn getData函数并使用mockResolvedValue来模拟实现。
https://stackoverflow.com/questions/73913544
复制相似问题