栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将TypeORM存储库注入NestJS服务以进行模拟数据测试

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将TypeORM存储库注入NestJS服务以进行模拟数据测试

假设我们有一个非常简单的服务,该服务通过id查找用户实体:

export class UserService {  constructor(@InjectRepository(UserEntity) private userRepository: Repository<UserEntity>) {  }  async findUser(userId: string): Promise<UserEntity> {    return this.userRepository.findOne(userId);  }}

然后,您可以

UserRepository
使用以下模拟工厂模拟(根据需要添加更多方法):

// @ts-ignoreexport const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({  findOne: jest.fn(entity => entity),  // ...}));

使用工厂可确保为每个测试使用新的模拟。

describe('UserService', () => {  let service: UserService;  let repositoryMock: MockType<Repository<UserEntity>>;  beforeEach(async () => {    const module: TestingModule = await Test.createTestingModule({      providers: [        UserService,        // Provide your mock instead of the actual repository        { provide: getRepositoryToken(UserEntity), useFactory: repositoryMockFactory },      ],    }).compile();    service = module.get<UserService>(UserService);    repositoryMock = module.get(getRepositoryToken(UserEntity));  });  it('should find a user', async () => {    const user = {name: 'Alni', id: '123'};    // Now you can control the return value of your mock's methods    repositoryMock.findOne.mockReturnValue(user);    expect(service.findUser(user.id)).toEqual(user);    // And make assertions on how often and with what params your mock's methods are called    expect(repositoryMock.findOne).toHaveBeenCalledWith(user.id);  });});

为了确保类型安全和舒适,您可以在模拟中使用以下类型(远非完美,当笑话本身在即将发布的主要版本中开始使用Typescript时,可能会有更好的解决方案):

export type MockType<T> = {  [P in keyof T]: jest.Mock<{}>;};


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号