繁体   English   中英

Angular 6 测试 Jasmine Karma:覆盖提供程序不起作用

[英]Angular 6 Testing Jasmine Karma: Override Provider Not working

所以我在网上看了很多问题,包括这个https://github.com/angular/quickstart/issues/320 ,我很难过......

我如何设置我的代码是我的主要描述创建了我的测试平台组件,在这里我为活动路由设置了我的 mockParams,所以我们可以 this.route.queryparams.subscribe(..),我的问题是我无法覆盖不同的 describe 或 'it' 块中的值。

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [RouterTestingModule
        })],
      providers: [
        { provide: ActivatedRoute, useValue: mockParams },
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
}));

这是我在不同的 NESTED 描述块中添加覆盖的示例...

beforeEach(() => {
      TestBed.overrideProvider(ActivatedRoute, 
      {useValue: newMockParams});
      TestBed.compileComponents();
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
});

几乎就像这根本没有运行...如果我重新使用 mockParams 并更改值,新的模拟参数不会更改,然后它将更改原始描述中的值,我真的必须重新创建我的组件吗?每个嵌套描述? 当我唯一需要更改的是提供程序时,我必须这样做是不正确的,我不确定此时 overrideProvider 甚至做了什么! 任何帮助将不胜感激!

更新了下面评论中提供的新信息。

我的建议是更改 route.queryParams 返回的值。 您在评论中提到您的 ngOnInit() 函数如下所示:

ngOnInit() {
    this.route.queryParams.subscribe(params => { this.value = params; });
}

如果在每次测试中运行 .detectChanges() 之前更改 queryParams observable 的返回值,这应该可以实现您想要的。 例如,这样的事情:

describe('MyComponent', () => {
    let mockActivatedRoute = {queryParams: of({old: 'test'})};
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    let route: ActivatedRoute;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [ ],
            providers: [
                { provide: ActivatedRoute, useValue: mockActivatedRoute },
            ]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        route = TestBed.get(ActivatedRoute);
    });

    it('ngOnInit should initialize and route params be intial values', () => {
        fixture.detectChanges(); // execute ngOnInit() in component
        expect(component.value).toEqual({old: 'test'}); // check that value is correct
    });
        it('ngOnInit should initialize and route params be changed values', () => {
        route.queryParams = of({new: 'newTest'/* mocked params */});
        fixture.detectChanges();
        expect(component.value).toEqual({new: 'newTest'}); // check that value is correct
    });
});

我在 stackblitz 中测试了这一切,以确保这一切都没有错误。 :) 这是链接: STACKBLITZ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM