Unit testing using ember-qunit controller action, accesses the store and methods

I have built a small Ember App. It has a controller which has an action named changeStatus(id). This method access the store and try to change an attribute value. I am relatively new to Ember. I don’t know whether best way is to test it with Integration test or unit test? And how to test with either way.

Here is the sample code

Controller: user.js

import Ember from 'ember';
    
    export default Ember.Controller.extend({
      
      actions: {
        changeStatus(id) {
          const oUser = this.store.peekRecord('user', id),
          let  bCurrentValue = oUser.get('active');
          if (bCurrentValue) {
            oUser.set('active', false);
          } else {
            oUser.set('active', true);
          }
            //oUser.save();
        },
      }
    });

Model: user.js

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
    
export default PatientIndexController;
    
    import Model from 'ember-data/model';
    import attr from 'ember-data/attr';
    
    export default Model.extend({
      active: attr('boolean'),
    });

Unit Test: user-test.js

import {moduleFor, test} from 'ember-qunit';
import Ember from 'ember';

moduleFor('controller:user', 'Unit | Controller | user', { });
test('Toggle user active status', function (assert) {
  const contollerUser = this.subject();
  contollerUser.send('changeStatus', 1);
  assert.equal(contollerUser.store.peekRecord('user', 1).get('active'), 'true or false');
  });

but I am not getting how to set some data to store. As when I call the function changeStatus() then it don’t know about user model.

How to set a proper test. Thanks in advance.

U can provide a stub of store, something like this

let oUser = Ember.Object.create({active: true});
contollerUser.set('store', {
    peekRecord(modelName, id) {
        assert.equal(modelName, 'user');
        assert.equal(id, 1);
        //return some mocked object
        return oUser;
    }
});
contollerUser.send('changeStatus', 1);
assert.equal(oUser.get('active'), false);

Hope that makes sense.

1 Like