【发布时间】:2022-02-10 05:20:56
【问题描述】:
我使用 prisma 与我的数据库交互,我想使用 jest-mock 来模拟 findMany 调用。 https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false
brands.test.ts
import { PrismaService } from "@services/mysql.service";
import { mocked } from "jest-mock";
import faker from "@faker-js/faker";
import { GetBrands } from "./brand";
jest.mock("@services/mysql.service");
/**
* @group unit
*/
describe("Brand", () => {
afterAll(async () => {});
const mockedPrismaService = mocked(PrismaService, true);
it("should get a list of brands", async () => {
const mockedData = [
{
id: faker.datatype.uuid(),
name: faker.datatype.string(),
image: {
source: "some_source",
dtype: "some_dtype",
},
},
];
//@ts-ignore - because of relational data mockedData.image
mockedPrismaService.brand.findMany.mockResolvedValueOnce(mockedData);
const [response, error] = await GetBrands();
console.log(response, error);
});
});
mysql.service.ts
import mysql from "mysql2/promise";
import { Config } from "@config";
import { PrismaClient, Prisma } from "@prisma/client";
export const MySQLEscape = mysql.escape;
export const MySQLPreparedStatement = mysql.format;
export const PrismaService = new PrismaClient({});
export const PrismaHelper = Prisma;
但是,当我运行此测试时,我收到以下错误。
TypeError: Cannot read properties of undefined (reading 'brand')
【问题讨论】:
-
包含
GetBrands函数的实现可能很有用 - 它是否使用您的PrismaService而不是构造一个新的PrismaClient()?
标签: node.js typescript unit-testing jestjs prisma