Search code examples
unit-testingnestjsmikro-orm

How to mock wrap().assign() of MikroORM when using with NestJS, the objective is unit testing a update method


I have a method like this

const user = await this.userRepository.findOneOrFail({ id });
wrap(user).assign(userData);
await this.userRepository.flush();
return await this.readById(user.id);

Similar to the one available in this official example, the example also implements unit testing for the service, but it doesn't implement a test for the update method.

I'd like to implement a unit test for the mentioned method, but when I try I get the following error

(0 , core_1.wrap)(...).assign is not a function
TypeError: (0 , core_1.wrap)(...).assign is not a function
    at UserService.updateUser (C:\Users\DanielMendesSechisnk\Projects\nestjs-rest-api\src\users\user.service.ts:37:16)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at Object.<anonymous> (C:\Users\DanielMendesSechisnk\Projects\nestjs-rest-api\src\users\tests\user.service.spec.ts:89:12)

What should I do to fix this problem?


Solution

  • insted of using wrap().assign() use em.assign() this will be easier to mock.

     const book = await em.findOneOrFail(Book, 1);
     //wrap(book).assign(new_version, { mergeObjects: true }); 
     em.assign(book, new_version, { mergeObjects: true })
     await em.flush();
    

    mocked entityManager on specs.ts

    let entityManagerMock = {
            findOne: jest.fn().mockResolvedValue(eventMock),            
            assign: jest.fn(),
        };