gpt4 book ai didi

ember.js - EmberJS 2.13单元测试:将同步代码包装在运行循环中吗?

转载 作者:行者123 更新时间:2023-12-02 06:02:09 25 4
gpt4 key购买 nike

在当前的Ember文档中,该操作已重复了几次,所以我觉得我一定缺少一些东西。让我们来看看simplest example I found

为什么对levelUp的调用被认为是异步的,以保证将其包装在运行循环中?
incrementProperty是同步的,据我所知,set也是如此(但我在这里可能会误会)

player.js

import DS from 'ember-data';

export default DS.Model.extend({
level: DS.attr('number', { defaultValue: 0 }),
levelName: DS.attr('string', { defaultValue: 'Noob' }),

levelUp() {
let newLevel = this.incrementProperty('level');
if (newLevel === 5) {
this.set('levelName', 'Professional');
}
}
});

player-test.js
import { moduleForModel, test } from 'ember-qunit';
import Ember from 'ember';

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

test('should increment level when told to', function(assert) {
// this.subject aliases the createRecord method on the model
const player = this.subject({ level: 4 });

// wrap asynchronous call in run loop
Ember.run(() => player.levelUp());

assert.equal(player.get('level'), 5, 'level gets incremented');
assert.equal(player.get('levelName'), 'Professional', 'new level is called professional');
});

最佳答案

首先,您绝对正确。在指南的任何地方都没有对它进行详尽的描述。

在测试模式下,自动运行被禁用。您可以从the guides进一步了解此内容。

但是,更改模型中的值会触发运行循环。 您可以在this twiddle上看到它。结果是:

Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run



(顺便说一句, setincrementProperty都会触发此运行循环作为您的猜测。)

然后是运行循环源:
  • DS.attr返回一个computed property with set
  • set函数triggers an event
  • 最后,a run loop is triggered
  • 关于ember.js - EmberJS 2.13单元测试:将同步代码包装在运行循环中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43794454/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com