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

7

我查看了许多网上的问题,包括这个 https://github.com/angular/quickstart/issues/320 但我被困住了...

我的代码设置是,在我的主要描述中创建测试组件,我在这里设置了模拟参数以获取活动路由,所以我们可以使用this.route.queryparams.subscribe(...)。我的问题是,在不同的描述或'it'块中无法覆盖值。

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

以下是我在不同的嵌套描述块中添加覆盖的示例...

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

好像这个根本不起作用……如果我重复使用mockParams并更改值,那么新的模拟参数不会改变,它只会改变原始描述中的值。难道我真的必须在每个嵌套的描述中重新创建我的组件吗?当我唯一需要更改的是提供程序时,这感觉不对。我现在不确定overrideProvider到底是什么!任何帮助都将不胜感激!


下面的回答有帮助吗? - dmcgrandle
1个回答

4

以下是评论中提供的新信息。

我的建议是更改route.queryParams返回的值。你在评论中提到你的ngOnInit()函数看起来像这样:

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

如果你在每个测试运行.detectChanges()之前更改queryParams可观察对象的返回值,那么就可以实现你想要的效果。例如,像这样:

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


我不使用get,我使用值方向ngOnInit() { this.route.query.subscribe(params => { this.value = params; }); } - yuffieh
我猜你实际上是指 this.route.queryParams.subscribe(params => { this.value = params; })?我会更新我的答案。 - dmcgrandle
是的,非常抱歉。您能告诉我您从哪里获取了“get”吗?我遇到了一个错误:“属性queryParams没有访问类型get”。 - yuffieh
当我回答你的评论时,我意识到我在使用spyOnProperty时有点过于复杂了。我有一个更简洁的解决方案,但我认为如果我在Stackblitz中展示给你看,然后你可以自己分叉并尝试不同的测试,这会更容易。我将用这个新信息更新我的答案。 - dmcgrandle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接