1
votes

Looking at the Ember tutorial on testing models, it treats incrementProperty as an async call. Why?

app/models/player.js

import Model from 'ember-data/model';
import { attr } from 'ember-data/model';

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

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

tests/unit/models/player-test.js

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

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
  run(() => player.levelUp());

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

The code appears to be synchronous as far as I can tell, but removing the run loop from the test does generate an error and the test fails:

Error: 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

1

1 Answers

0
votes

To quote the Run Loop guides, operations are batched to optimize rendering:

Ember's internals and most of the code you will write in your applications takes place in a run loop. The run loop is used to batch, and order (or reorder) work in a way that is most effective and efficient.

Why is the run loop useful? Very often, batching similar work has benefits. Web browsers do something quite similar by batching changes to the DOM.

What happens in tests is that the runloop does not automatically run, so you need run to flush the queues. I believe there is work underway to remove this differing behaviour of the testing environment.