Testing controllers

Controllers should be tested in your application. In this recipe, we'll test some basic actions from a controller.

How to do it...

  1. Create a new index controller:
    $ ember g controller index
    

    This creates a new controller called index.

  2. In the index controller, add a new property and action:
    // app/controllers/index.js
    import Ember from 'ember';
    
    export default Ember.Controller.extend({
        myValue: 'value',
        actions:{
          pressed(value){
            this.set('myValue',value);
          }
        }
    });

    This controller has one property named myValue. Another action called pressed changes the value of myValue to whatever value is passed in the function.

  3. Update the index unit test. Add a few tests for the action and property:
    // tests/unit/controllers/index-test.js
    import { moduleFor, test } from 'ember-qunit';
    
    moduleFor('controller:index', 'Unit | Controller | index', {
        // Specify the other units that are required for this test.
        // needs: ['controller:foo']
    });
    
    // Replace this with your real tests.
    test('it exists', function(assert) {
        let controller = this.subject();
        assert.ok(controller);
    });
    
    test('check property', function(assert) {
        assert.expect(2);
        let controller = this.subject();
        assert.equal(controller.get('myValue'),'value');
        controller.send('pressed','newValue');
        assert.equal(controller.get('myValue'),'newValue');
    });
  4. The moduleFor helper is used here for controllers. The first test checks to make sure that the controller exists:
    …
    test('check property', function(assert) {
        assert.expect(2);
        let controller = this.subject();
        assert.equal(controller.get('myValue'),'value');
        controller.send('pressed','newValue');
        assert.equal(controller.get('myValue'),'newValue');
    });

    This test creates an instance of the controller with this.subject. The initial value is checked to make sure that it's correct. To send an action to the controller, the controller.send method is called. The send method can take one or more parameters. The first is the name of the action to be triggered. This is followed by any values that should be passed in the method.

  5. Run ember server and navigate to /tests. This will display the passed tests:
    How to do it...

    This message shows that all tests passed

How it works...

Controller tests are very similar to the unit tests that we discussed before. They use QUnit's moduleFor helper. In a controller, we can test the properties or actions and make sure that the results are as we expected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset