在 EmberJS 中测试计算模型的 hasMany 关系

Test computing a model's hasMany relationship in EmberJS

我正在尝试在模型中为计算的 属性 添加单元测试,它查找一个 属性 这是一个 hasMany 关系以检索其中一个基于另一个 属性 标准。

主要代码如下:

import DS from 'ember-data';

import {computed} from '@ember/object';

export default DS.Model.extend({
    gamePlayers: DS.hasMany('gamePlayer', { async: false }),
    sessionUserId: DS.attr('number'),

    heroPlayer: computed('sessionUserId', 'gamePlayers', function() {
        const userId = parseInt(this.get('sessionUserId'));
        const heroPlayer = this.get('gamePlayers').find(player => player.get('userId') === userId);
        return heroPlayer;
    })
});

这是我尝试测试它的方式:

import { moduleForModel, test } from 'ember-qunit';
import { run } from '@ember/runloop';

moduleForModel('game', 'Unit | Model | game', {
  // Specify the other units that are required for this test.
  needs: ['model:gamePlayer']
});

test('heroPlayer retrieves the player where userId matches the session', function(assert) {
    const store = this.store();
    const done = assert.async();
    run(() => {
        const gamePlayers = [store.createRecord('gamePlayer', {userId: 111}), store.createRecord('gamePlayer', {userId: 222})];
        const sessionUserId = 111;
        const model = this.subject({ gamePlayers, sessionUserId });
        assert.equal(111, model);
        done(); 
    })
});

但是无论我如何实施测试,我总是遇到不同的问题,我无法在单元测试中创建 gamePlayer 对象。

在这种情况下,ember 测试套件会丢弃一堆像这样的 backbunner 错误:

Expected:   
{
  "__OVERRIDE_OWNER__ember1517897244339342530367001__": {
    "__POST_INIT__ember15178972443391088345028564__": function(){
...
    at http://localhost:7357/assets/tests.js:762:20
    at Backburner._run (http://localhost:7357/assets/vendor.js:20474:35)
    at Backburner.run (http://localhost:7357/assets/vendor.js:20197:25)

覆盖这种场景的 ember 方法是什么?我正在使用 Ember 2.18

好的,方法是正确的,但是 运行 中的代码不正确,看起来我正在尝试 assert.equal 模型而不是 heroPlayer 属性 ,这个 snnipet 解决了这个问题:

run(() => {
    const gamePlayers = [store.createRecord('gamePlayer', {userId: 111}), store.createRecord('game-player', {userId: 222})];
    const sessionUserId =  111;
    const model = this.subject({ gamePlayers, sessionUserId });
    assert.equal(111, model.get('heroPlayer.userId'));
    done();
});