如何在 Ember js 控制器功能测试中调用路由功能?
Posted
技术标签:
【中文标题】如何在 Ember js 控制器功能测试中调用路由功能?【英文标题】:How to call a route function in Ember js controller function test? 【发布时间】:2021-10-30 09:54:54 【问题描述】:我有一个 ember js 控制器函数 onRefreshClicked
,它在路由 refreshData
内调用一个函数。
我想为此控制器的功能运行单元/集成测试,但它找不到路由功能的链接并出错。
如何在 ember v3.2.x
中执行此操作?
插件/控制器/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!
插件/路由/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);
);
);
错误
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)
【问题讨论】:
【参考方案1】:我最喜欢的技术是在路线的模型数据上定义方法,如下所示:
async model()
return
myMethod: () =>
;
然后,在您的控制器中,您可以通过this.model.myMethod()
调用
【讨论】:
以上是关于如何在 Ember js 控制器功能测试中调用路由功能?的主要内容,如果未能解决你的问题,请参考以下文章