Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 无法读取属性';导航';在角度测试中进行单元测试时未定义的错误_Angular_Karma Jasmine_Angular Test - Fatal编程技术网

Angular 无法读取属性';导航';在角度测试中进行单元测试时未定义的错误

Angular 无法读取属性';导航';在角度测试中进行单元测试时未定义的错误,angular,karma-jasmine,angular-test,Angular,Karma Jasmine,Angular Test,为什么在对需要调用的函数进行单元测试时会出现此错误:以下是我的代码,首先是.spec.ts的代码: it(' doit appeller le serveur quand le boutton ok est cliqué, pour envoyer l option du choix du code', () => { let spy = spyOn(authService, 'choixReceptionCode').and.callFake(t => { // on es

为什么在对需要调用的函数进行单元测试时会出现此错误:以下是我的代码,首先是.spec.ts的代码:

it(' doit appeller le serveur quand le boutton ok est cliqué, pour envoyer l option du choix du code', () => {
  let spy = spyOn(authService, 'choixReceptionCode').and.callFake(t => {
  // on est pas besoin de se qui retourner du serveur l essentiel la fonction a ete appelle 
  return Observable.empty();
});

component.choix('mail');
  // comme ça on a testé si la fonction 'connexion' a été appelle ou nn
  expect(spy).toHaveBeenCalled();
});
下面是component.ts中的函数:

choix(choice:string)
{
  console.log("ggggggggg"+choice);
  this.router.navigate(['saisirCode']);
  this.choiceReceptionCode.choix=choice;
  this.choiceReceptionCode.user=this.serviceAuthentification.getUserId();
  this.serviceAuthentification.choixReceptionCode(this.choiceReceptionCode).subscribe(
  (data)=>{
      console.log("the response in choixReceptionCode");
      console.log(data);     


  },
  (error)=>{
      console.log("Error in choixReceptionCode ");
      console.log(error);
  });
}
执行ng测试时,我发现此错误,

我知道问题出在这方面:

this.router.navigate(['saisirCode']);
在component.ts文件中,因为当我注释它时,它是测试通过的,所以如何解决它


非常感谢

您可以尝试为路由器提供模拟

比如:

let router = jasmine.createSpyObj("Router", ["navigate"]);
然后:

router.navigate.and.callFake(()=>Observable.of(your stubbed data to return here));
然后通过注入路由器模拟来创建组件的实例

let component = new MyComponent(router);

此时,您可以调用
this.router.navigate
方法,因为
this.router
将引用您已经模拟和提供的注入服务。

非常感谢;我找到了一个解决方案,我改变了这个指令的位置:this.router.navigate(['saisirCode']);因为我需要以任何方式对用户进行路由,所以在调用服务器时,我对用户进行路由,并使我的http.post变得简单,而服务器的功能是callFake。