Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.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 6中模拟Jasmine测试的路由器订阅_Angular_Unit Testing_Jasmine - Fatal编程技术网

在Angular 6中模拟Jasmine测试的路由器订阅

在Angular 6中模拟Jasmine测试的路由器订阅,angular,unit-testing,jasmine,Angular,Unit Testing,Jasmine,我有两个失败的单元测试用于编译我的组件。无论哪种情况,都是由于我的代码试图引用router.events或router.params: 路由器参数 路由器事件 我的测试设置如下: let router; router.events = of(new NavigationEnd(0, 'http://localhost:4200/', 'http://localhost:4200/')); beforeEach(async(() => { TestBed.configureTestin

我有两个失败的单元测试用于编译我的组件。无论哪种情况,都是由于我的代码试图引用router.events或router.params:

路由器参数

路由器事件

我的测试设置如下:

let router;
router.events = of(new NavigationEnd(0, 'http://localhost:4200/', 'http://localhost:4200/'));

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
        ...
      { provide: Router, useValue: router }
    ]
  })
    .compilecomponents();
}));
然而,当我运行我的jasmine测试时,我得到一个错误,说我“无法读取未定义的”的属性“subscribe”。我似乎找不到任何答案或指导来知道我可能会错在哪里。有人能提供一些关于如何以不同方式设置的信息吗?

您可以创建一个RouterStub类,并在测试中初始化模拟路由器的值

class RouterStub {
   config = [];
   events = of({});
   params = of({});
   url = '';
   resetConfig() {}
   navigate() { }
}
您可以根据在TestClass中的使用情况模拟url、params等值。 在TestBed配置中使用它:

beforeEach(async(() => {
           TestBed.configureTestingModule({
           declarations: [
            ...
             { provide: Router, useValue: new RouterStub()}
          ]
        })
        .compilecomponents();
       }));

我创建了一个模拟RouterStub类,并在我的useValue for Router中使用它。。。。但我仍然收到这些未定义的错误。请检查您是否订阅组件中的ActivateRoute或Router。根据需要进行模拟。实际上,这解决了一个未定义的问题,另一个仍然失败,但这似乎解决了我最初的问题。是的,我团队的另一个开发人员将activatedRoute变量命名为“route”,并拥有一个名为router的路由器。我的错误你的回答是正确的。这在
class RouterStub {
   config = [];
   events = of({});
   params = of({});
   url = '';
   resetConfig() {}
   navigate() { }
}
beforeEach(async(() => {
           TestBed.configureTestingModule({
           declarations: [
            ...
             { provide: Router, useValue: new RouterStub()}
          ]
        })
        .compilecomponents();
       }));