Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
如何使用 overrideModule / overrideProvider 等方法
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ActivatedRoute } from '@angular/router';
import { DemoComponent } from './demo.component';
import { of } from 'rxjs/observable/of';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [DemoComponent],
providers: [
{
provide: ActivatedRoute,
useValue: {
data: of({ actionType: 'abc' })
}
}
]
})
class SomeModule {}
describe('DemoComponent', () => {
let component: DemoComponent;
let fixture: ComponentFixture<DemoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({ imports: [SomeModule] });
}));
describe('使用原本的 module', () => {
beforeEach(() => {
fixture = TestBed.createComponent(DemoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('actionType should equal abc', async(() => {
expect(component.actionType).toBe('abc');
}));
});
describe('使用修正後的 module', () => {
beforeEach(() => {
TestBed.overrideModule(SomeModule, {
set: {
providers: [
{
provide: ActivatedRoute,
useValue: {
data: of({ actionType: '123' })
}
}
]
}
});
});
beforeEach(() => {
fixture = TestBed.createComponent(DemoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('actionType should equal 123', async(() => {
expect(component.actionType).toBe('123');
}));
});
describe('使用修正後的 provider', () => {
beforeEach(() => {
TestBed.overrideProvider(ActivatedRoute, {
useValue: {
data: of({ actionType: 'def' })
}
});
});
beforeEach(() => {
fixture = TestBed.createComponent(DemoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('actionType should equal def', async(() => {
expect(component.actionType).toBe('def');
}));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment