【发布时间】:2020-02-10 22:27:12
【问题描述】:
我正在一个 nativescript-angular 组件上编写单元测试来测试一些事情 1) 登录表单的提交函数和 2) 成功登录后的路由器导航/视图。
在我使用来自nativescript-angular/router 的RouterExtensions 进行导航的组件中
在组件构造函数中,我使用默认用户凭据初始化组件并将路由器扩展作为参数传递。
constructor(private page: Page,private routerExtensions: RouterExtensions){
this.page.actionBarHidden = true;
this.user = new User();
this.user.email = "dennis@gmail.com";
this.user.password = "password";
}
成功登录后,我将用户导航到home 页面,其逻辑如下所示。
submit(){
if (!this.user.email || !this.user.password) {
this.alert("Please provide both an email address and password.");
return;
}
this.processing = true;
if(this.isLoggingIn){
this.login();
}else{
this.register();
}
}
login() {
console.log(this.user)
if(this.user){
this.processing = false;
this.routerExtensions.navigate(["/home"], { clearHistory: true });
}else{
this.processing = false;
this.alert("Unfortunately we could not find your account.");
}
}
我正在使用 mocha 进行测试,目前我的单元测试看起来像这样
var reflect = require("reflect-metadata");
var component = require("../app/login/login.component");
describe("Test for Login component", ()=>{
var appComponent;
beforeEach(()=>{
appComponent = new component.LoginComponent();
});
it("Should Login User", ()=> {
appComponent.submit();
assert.equal(appComponent.user.email,"dennis@gmail.com")
assert.equal(appComponent.user.password,"password")
});
it("Should navigate user to home page",()=>{
// Logic for testing that the view is home page.
})
});
在运行测试时出现此错误
TypeError: Cannot read property 'navigate' of undefined
我了解此错误是由以下行引起的:
this.routerExtensions.navigate(["/home"], { clearHistory: true }); 在 login() 方法中,因为在评论它时测试通过了。
我不确定如何编写单元测试来测试页面路由和查看用户所在的位置。如何模拟导航问题。谢谢
【问题讨论】:
-
您找到解决方案了吗?
-
这是我所做的
let router = jasmine.createSpyObj("Router", ["navigate"]);然后在测试功能expect(router.navigate).toHaveBeenCalledWith(["/home"], { clearHistory: true });
标签: angular unit-testing mocha.js nativescript nativescript-angular