【发布时间】:2017-02-21 17:46:35
【问题描述】:
我的 Angular 应用程序中有以下控制器。
m = angular.module "myapp.dashboards"
m.directive "lkDashboardElement", (
$timeout
MyAppSettings
)->
scope:
dashboard: "="
element: "="
dashboardController: "="
elementLoaded: "&"
link: ($scope, $el)->
if MyAppSettings.shouldCalculateTableWidth
document.addEventListener "dashboard.element.rendered", =>
$timeout(->
..
..
)
我删除了很多东西,所以只显示了重要的部分。我遇到的问题与我对 Angular $timeout 的使用有关。我目前正在检查某个条件shouldCalculateTableWidth,如果我看到一个事件触发,我会立即超时。
目前我正在尝试编写一个单元测试来检查是否正在使用$timeout。
这是我的测试:
describe "in a phantomjs context", ->
beforeEach ->
# This sets our Phantom rendering context to true for testing purposes
MyAppSettings._setIsPhantomRendering(true)
afterEach ->
MyAppSettings._setIsPhantomRendering(false)
it "uses $timeout (instead of applyAsync) for adjusting table widths", ->
# Creates a dummy dashboard
dashboardController.queryMap = {1: {view: "foo", model: "bar"}}
dashboard.elements = [{id: 1}]
spyOn($timeout, "flush")
expect($timeout.flush).toHaveBeenCalled()
我要做的只是测试这段代码中是否使用了$timeout,因为当我在 Phantom(图像渲染库)上下文中时,某些图像的渲染方式很重要。当我运行测试时,我收到以下错误:
Expected spy flush to have been called.
我遇到的具体问题是测试中的以下两行:
spyOn($timeout, "flush")
expect($timeout.flush).toHaveBeenCalled()
首先,我不相信我为$timeout 调用了正确的方法。在我的控制器中非常清楚,我打电话给$timeout,而不是$timeout.flush。其次,对于 Jasmine Spys,您不能只使用 spyOn 和 $timeout,因为它需要对类和方法的引用。
所以我不太确定如何继续前进。我将不胜感激 - 谢谢!
【问题讨论】:
-
flush是一个只存在于ngMock中的方法,可以从测试中调用。所以监视刷新只检查你是否从测试中调用它。这是你的测试,你知道你做过/没做过,那你为什么要检查它?
标签: javascript angularjs unit-testing jasmine karma-jasmine