Search code examples
ember.jsqunitember-testing

How to test route's willTransition action in Ember?


How can I test this code in Ember? Explain me please the concept, in general.

// app/routes/products/new.js
import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.createRecord('product');
  },
  actions: {
    willTransition() {
      this._super(...arguments);
      this.get('controller.model').rollbackAttributes();
    }
  }
});

I have no idea how to make this. May be stub model in route? I found that store is not available in route test.

After Ruby and RSpec, all these new javascript world is confusing a little bit) But I'd like to learn it anyway.


Solution

  • In unit tests the idea is to stub all external dependencies. In ember you can do this:

    // tests/unit/products/new/route-test.js
    test('it should rollback changes on transition', function(assert) {
      assert.expect(1);
      let route = this.subject({
        controller: Ember.Object.create({
          model: Ember.Object.create({
            rollbackAttributes() {
              assert.ok(true, 'should call rollbackAttributes on a model');
            }
          })
        })
      });
      route.actions.willTransition.call(route);
    });
    

    Basically you stub controller and model passing them to this.subject(), then call whatever function you are testing (in this case you have to use call or apply to call an action with the correct scope), and then assert that rollbackAttributes() was called.

    assert.expect(1); at the start of a test tells QUnit to wait for exactly 1 assertion.