我试图在Jest中模拟Typeorm模块的一个功能,并且我想以尽可能干净的方式来实现它。我所创造的成功之处是:
jest.mock("typeorm", () => ({
__esModule: true,
getCustomRepository: jest.fn(),
PrimaryGeneratedColumn: jest.fn(),
Column: jest.fn(),
CreateDateColumn: jest.fn(),
UpdateDateColumn: jest.fn(),
Entity: jest.fn(),
EntityRepository: jest.fn(),
Repository: jest.fn(),
}));但是,我只想模拟getCustomReposity,而当我只为该函数保留模拟时:
jest.mock("typeorm", () => ({
__esModule: true,
getCustomRepository: jest.fn(),
}));测试甚至不运行,因为实体和存储库使用来自Typeorm的一些装饰器和类。我还试图为整个模块生成模拟:
jest.mock("typeorm", () => jest.createMockFromModule("typeorm"));生成的模拟装饰器出现了错误:
TypeError: decorator is not a function
2 |
3 | @Entity({ name: "users" })
> 4 | export class User {有没有办法用比我更干净的方式创建这样的模拟呢?
发布于 2021-05-15 03:18:14
您的代码需要的不仅仅是您所模仿的内容。
如果你嘲笑
jest.mock("typeorm", () => ({
__esModule: true,
getCustomRepository: jest.fn(),
}));然后在您的代码中,import { Entity} from 'typeorm';,现在Entiry是未定义的。除了getCustomRepository以外,其他属性也是如此。
您可以用第一个解决方案解决这个问题,也可以模拟您想要模拟的内容,并将另一个属性作为实际的逻辑返回。
jest.mock('typeorm', () => {
const actual = jest.requireActual('typeorm');
return {
...actual,
getCustomRepository: jest.fn(),
}
});或模拟typeorm的所有属性
jest.mock('typeorm');发布于 2022-02-16 11:57:54
您还可以以这种方式模拟getCustomRepository:
import typeorm = require('typeorm');
describe('Your test suit', () => {
beforeAll(() => {
typeorm.getCustomRepository = jest.fn().mockReturnValue({
yourMethod: jest.fn(),
});
});
it('your test case', () => {});
});https://stackoverflow.com/questions/67509778
复制相似问题