javascript - 如何测试 expect().toHaveBeenCalled() - Angular2+
问题描述
我想测试我的外部函数是否已被调用,但我似乎没有弄清楚......
我目前收到失败消息:
预期的间谍登录已被调用。
测试
fit('should login with valid form & credentials', inject([AuthService],
(authServ: AuthService) => {
component.onSubmit(validFormGoodCreds);
spy = spyOn(authServ, 'login');
expect(spy).toHaveBeenCalled();
expect(hideMsg).toEqual(true);
}));
登录组件
...
onSubmit(form: NgForm) {
if (form.valid) {
this.authService.login(this.user.username, this.user.password)
.subscribe(
data => {
/* TODO: Navigate to holding page etc */
// Hide any error message that was previously shown
this.hideErrorMsg = true;
},
err => {
// Change error message to be shown
this.errorMessage = 'Either username or password were incorrect';
// Show the error message
this.hideErrorMsg = false;
}
);
}
解决方案
尝试这个:
spy = spyOn(authServ, 'login').and.returnValue(true);
expect(authServ.login).toHaveBeenCalled();
这是 Angular 5+ 的一个很好的测试指南:https ://codecraft.tv/courses/angular/unit-testing/mocks-and-sies/
推荐阅读
- html - Selectors for divs with specific data attributes
- r - 在 R 中,ts.plot( gpars col=c("red","blue") 只返回一个彩色图)
- vue.js - 是否有 Vue.js 表单验证库在模糊时显示错误,修复后立即隐藏错误
- extjs - 如何在 ExtJS Modern 中的控制框周围设置边框?
- java - java JList不会刷新,在调试器中工作
- verilog - 无法在 verilog 中详细说明实例化模块
- sql-server-2012 - 有条件地从一张表中汇总一列中一组的值
- python - 尝试使用给定列表更新年龄值
- pointers - 为什么使用不安全代码的二叉树在调试模式下有错误的内存访问,但没有释放?
- ruby-on-rails - 在 ActiveRecord 查询执行之前调用 Oracle 包函数