试图模拟node.js/express中的函数返回



我正在测试我在node.js/Express中编写的应用程序。

我想模拟我为开发目的设置的模拟存储库的返回。

模拟回购:

let dogs = [];
export const getDogs = () => {
return dogs;
};
export const setDogs = (updatedDogs) => {
dogs = updatedDogs;
};

我正在导入函数来模拟我的测试文件中的返回值;

import * as sut from "../dogs.js";
import * as dogsRepo from "../../repositories/dogs.js";
import { mockRequest, mockResponse } from "mock-req-res";
import { jest } from "@jest/globals";
describe("dogs controller", () => {
describe("getDogs", () => {
test("should return dogs", () => {
// Arrange
const req = mockRequest();
const res = mockResponse();
// dogsRepo.getDogs = jest.fn().mockReturnValue([]);
// jest.spyOn(dogsRepo, "getDogs").mockReturnValue([]);
jest.spyOn(dogsRepo, "getDogs").mockImplementation(() => []);
//Act
sut.getDogs(req, res);
});
});
});

我只想让我的测试模拟来自存储库的返回值[]。我在react项目中做过很多次,但这是我第一次在node.js中这样做。

我试着用三种不同的方式模拟函数的返回,每一种都给了我错误;

TypeError:无法给对象'[object Module]'的只读属性'getDogs'赋值

我在控制器(sut)中以相同的方式导入,它按预期工作,因此我可以合理地确信我所采用的导入/导出风格正在工作。

import * as dogsRepo from "../repositories/dogs.js";
export const getDogs = (req, res) => {
const dogs = dogsRepo.getDogs();
res.send(dogs);
};

我做错了什么?

它是否与我的package.json中的配置有关?

"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "nodemon index.js"
},

据我所知,您没有嘲笑模块。试试下面的内容:

jest.mock('../../repositories/dogs');

你的测试应该有效。有关更多信息,请参阅官方jest文档。

最新更新