简体   繁体   English

单元测试 mirkoORM 实体

[英]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.我正在尝试对 MikroORM 实体中的方法进行单元测试,从而用测试数据填充 mikroORM collection字段。 (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 ?知道如何正确地对 MikroORM 实体进行单元测试吗?

You need to initialize the ORM first to work with the entities.您需要先初始化 ORM 才能使用实体。 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.没有它,就没有元数据,也没有打补丁的实体原型——这是传播工作所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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