【发布时间】:2017-06-08 05:12:21
【问题描述】:
我正在尝试测试在$onInit 中解决了一个promise 后一个值是否更改为true。我正在尽我所能关注example in this Stack Overflow question/answer。这是我的代码:
class TestCtrl {
constructor(SearchService) {
this.testValue = false;
this.SearchService = SearchService;
}
$onInit() {
this.SearchService.getResults()
.then(function () {
this.testValue = true;
});
}
}
TestCtrl.$inject = ['SearchService'];
这是我正在尝试运行的测试(使用 mocha、chai、sinon):
it('should work', function() {
ctrl = $componentController('test', {
SearchService: SearchService
}, {});
sinon.stub(SearchService, 'getResults').resolves({response:{data: 'data'}});
ctrl.$onInit();
$rootScope.$apply();
ctrl.testValue.should.equal(true);
});
我应该在then 中测试ctrl.testValue 吗?另外,使用this example 是不是一个坏主意,因为该示例没有使用带有$onInit 生命周期钩子的组件?
根据我读到的no,“不要在测试中使用 expect 。”但根据我read elsewhere 的内容,我不太确定。
如果我在如何测试承诺(也许存根不是要走的路?)和/或如何测试 $onInit 生命周期钩子中发生的事情中遗漏了一些明显的东西,我不会感到惊讶。
如果问题需要更多详细信息,请提出,我会尽力添加。
【问题讨论】:
-
没有一般原因您不应该在
.then中使用expect。您链接到的问题中的 OP 是使用 Jasmine,而不是 Mocha。也许 Jasmine 不擅长处理承诺(这将是在then中不使用expect的特殊原因,而不是一般原因),但 Mocha 确实如此不擅长处理承诺。你只需要记住回报承诺。 -
为什么要打电话给
$rootScope.apply()? -
只是为了详细说明 Louis 的回答:Mocha 和 Jasmine 都可以通过让框架将回调传递给测试代码调用的测试函数来处理任何类型的异步代码(包括 Promises)。测试成功完成。 Mocha 有一些特殊的处理方式,它还允许它通过返回承诺来放弃回调,这使得测试更加顺畅(见下文)。
-
您在
then处理程序的匿名函数中使用this。this.testValue = true;将分配给window,而不是您的TestCtrl实例。为了让this引用TestCtrl实例,您应该尽可能使用箭头函数,或者将this包装在变量中,例如var ctrl = this
标签: angularjs unit-testing promise mocha.js sinon