简体   繁体   中英

Unit testing mirkoORM entities

I'm trying to unit test a method in a MikroORM entity and thus to populate a mikroORM collection field with test data. (I use jest) :

describe('Team Tests', () => {
    it('isLeader should return true when given user is the team leader', () => {
       // Given
        const team = new Team('Test team');
        const user = new User('Test User', 'test@test.fr');

        team.members.add(new TeamMember(user, TeamRole.Leader));

        // When
        const result = team.isLeader(user.userId);

        // Then
        expect(result).toBe(true);
    });
});

However, when I run my test, I hit the following error when adding the data to the collection :

Cannot read properties of undefined (reading 'properties')
TypeError: Cannot read properties of undefined (reading 'properties')
    at Collection.get property [as property] (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\ArrayCollection.js:123:44)
    at Collection.validateItemType (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:317:71)
    at C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:111:40
    at Array.forEach (<anonymous>)
    at Collection.add (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:111:19)
    at Object.<anonymous> (C:\Users\arsen\git\HorizonWeb\api\src\teams\team.entity.spec.ts:11:22)
    at Promise.then.completed (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\utils.js:390:28)
    at new Promise (<anonymous>)
    at callAsyncCircusFn (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\utils.js:315:10)
    at _callCircusTest (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\run.js:218:40)

Any idea of how to properly unit test a MikroORM entity ?

You need to initialize the ORM first to work with the entities. For unit tests where you do not want to touch the database, you can use the second parameter to not connect to the database, but the entity discovery needs to happen. Without that there is no metadata and no patched entity prototypes - and that is needed for propagation to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM