我试图在模型中为计算属性添加单元测试,在该模型中查找属性为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 2.18
答案 0 :(得分:0)
好的,所以方法是正确的,但运行中的代码不正确,看起来我试图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();
});