mardi 31 août 2021

How to call a route function in Ember js controller function test?

I have an ember js controller function onRefreshClicked which call a function inside the route refreshData.

I would like to run a unit/integration test for this controller's function, but then it cannot find the link to the route's function and error out.

How do I do this in ember v3.2.x?

addon/controllers/scan-monitor.js

import { action } from '@ember/object';
export default class ScanMonitorController extends Controller {

  @action
  onRefreshClicked(clickEvent) {
    debugger;
    clickEvent.preventDefault();
    // Some extra logic
    this.send('refreshData'); // ----> ERROR OUT!
  }
}

addon/routes/scan-monitor.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class ScanMonitorRoute extends Route {
  @service store;

  @action
  refreshData() {
    debugger;
    this.refresh();
  }
}

tests/unit/controllers/scan-monitor-test.js

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Controller | scan-monitor', function (hooks) {
  setupTest(hooks);

  let scanMonitorController;

  hooks.beforeEach(function () {
    scanMonitorController = this.owner.lookup('controller:scan-monitor');
  });

  test('controllers.scan-monitor.onRefreshClicked', function (assert) {
    debugger;
    // Assigning or not assigning the route doesn't make any difference.
    // scanMonitorController.route = this.owner.lookup('route:scan-monitor');

    scanMonitorController.onRefreshClicked(new MouseEvent('click', {}));

    assert.ok(scanMonitorController);
  });
});

The error

TypeError: Cannot read property 'trigger' of undefined
    at Router.send (http://localhost:7357/assets/vendor.js:31600:28)
    at ScanMonitorController.send (http://localhost:7357/assets/vendor.js:34358:16)
    at ScanMonitorController.onRefreshClicked (http://localhost:7357/assets/vendor.js:173217:12)
    at Object.<anonymous> (http://localhost:7357/assets/tests.js:527:29)



Aucun commentaire:

Enregistrer un commentaire