You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// UserResolver.test.tsimport{ConnectionManager}from'typeorm';// mocked repositoryclassMockUserRepository{staticfindOne: jest.MockedFunction<typeofUserRepository.prototype.findOne>;staticsetupMocks(){this.findOne=jest.fn().mockResolvedValue(undefined);}}describe('UserResolver class',()=>{beforeAll(()=>{// This, as we know, is not enough for mocking @InjectRepository()// Container.set(UserRepository, MockUserRepository);// this will be used only once during the initial import so there is no need to put this in beforeEachContainer.set(ConnectionManager,{has: (connectionName: string)=>true,get: (connectionName: string)=>({getRepository: (entityType: any)=>{console.warn(`No mock repository found for ${entityType}`);},getMongoRepository: (entityType: any)=>{console.warn(`No mock repository found for ${entityType}`);},getTreeRepository: (entityType: any)=>{console.warn(`No mock repository found for ${entityType}`);},getCustomRepository: (repositoryType: any)=>{switch(repositoryType){caseUserRepository:
returnMockUserRepository;// here we mock our repositorydefault:
console.warn(`No mock repository found for ${repositoryType}`);}},}),});});beforeEach(()=>{MockUserRepository.setupMocks();});it('should pass',async()=>{MockUserRepository.findOne.mockResolvedValue({});await<test>expect(MockUserRepository.findOne).toHaveBeenCalledWith({email: '...'});});});
A better way of mocking is clearly needed. It seems that the selected solution above does not fully solve the issue since you need to also mock the entire ConnectionManager. In other words, with the above solution only, any getConnection() calls would fail as it is not mocked (not to mention any other methods).
Better way means, you only mock what you need to mock.
Pretty much like
Function
getRepository
from src/decorators/InjectRepository.ts seems to be problematic.I dealt with it like this:
if you inject repository as:
then this should work:
Originally posted by @kajkal in #33 (comment)
A better way of mocking is clearly needed. It seems that the selected solution above does not fully solve the issue since you need to also mock the entire
ConnectionManager
. In other words, with the above solution only, anygetConnection()
calls would fail as it is not mocked (not to mention any other methods).Better way means, you only mock what you need to mock.
Pretty much like
would be ideal.
The text was updated successfully, but these errors were encountered: