我有一个猫鼬模型,设置如下,
模型.TS
export interface LocationInterface extends mongoose.Document {
name: string;
description: string;
}
export const Location = mongoose.model<LocationInterface>(
process.env.DB_CONTAINER || "Null",
locationSchema
);
然后我嘲笑它,
https://jestjs.io/docs/en/mock-function-api
//tests.ts
Import Location from ‘./model’;
Location.create = jest.fn();
然后我想确认它何时发送 json 响应,它收到的正常。
it("should return json body in response", () => {
Location.create. // => no mockReturnValue method is avaliable here??
我已经尝试了以下方法,但它不起作用。 如何使用 Jest 模拟 ES6 模块导入?
jest.mock("./model", () => ({
Location: jest.fn()
}));
我尝试使用导出默认位置,这也不起作用。
我尝试了以下方法,但也没有奏效。
jest.mock("../../../src/models/location.model", () => Location.create);
我从 https://codewithhugo.com/jest-mock-spy-module-import/尝试了以下内容
import * as mockDB from "./model";
jest.mock('.model', () => ({
get: jest.fn(),
set: jest.fn()
}));
expect(mockDb.Location.create. // -> No Methods available
这篇博客文章解决了我所有的问题。
https://dev.to/terabaud/testing-with-jest-and-typescript-the-tricky-parts-1gnc
import { mocked } from "ts-jest/utils";
import Location from "/model";
jest.mock("../../../src/models/location.model", () => {
return jest.fn();
});
it("should recieve a code 201 and json response", async () => {
// Mock Response
mocked(Location.create).mockImplementation(
(): Promise<any> => {
return Promise.resolve(dummyRecord);
}
);
const response = await DatabaseService.createRecord(dummyRecord, Location);
expect(response).toStrictEqual({
code: 201,
data: dummyRecord
})
});