我在這個專案中添加了一個route.queryParamMap.pipe(..) 。但是,現在組件的單??元測驗失敗并出現TypeError: Cannot read properties of undefined (reading 'pipe') inside "should create"。我無法找到適當的解決方案。我必須在單元測驗中實施哪些更改?如何模擬 ActivatedRoute 或 queryParamMap?
這是組件類:
export class ContainerComponent implements OnInit {
public tab$: Observable<string> = this.route.queryParamMap.pipe(
map(params => params.get('type')),
distinctUntilChanged()
);
// ...
constructor(private readonly route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
//...
}
這是沒有匯入的單元測驗:
describe('ContainerComponent', () => {
let component: ContainerComponent;
let fixture: ComponentFixture<ContainerComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
NgMaterialModule,
],
providers: [
{
provide: Router,
useValue: {navigate: jest.fn()},
},
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: {
type: 'placeholder',
}
},
routeConfig: {
path: '',
}
}
},
],
declarations: [
ContainerComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ContainerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
uj5u.com熱心網友回復:
您提供以下代碼作為 ActivatedRoute:
{
snapshot: {
queryParams: {
type: 'placeholder',
}
},
routeConfig: {
path: '',
}
}
因此,您的 queryParams 是不可觀察的,因此您會收到錯誤訊息。要解決這個問題,您可以將 RouterTestingModule 匯入您的測驗套件,或者您可以使用 observable 模擬 queryParams。這意味著而不是
{
type: 'placeholder',
}
使用以下代碼:
of({ type: 'placeholder' })
uj5u.com熱心網友回復:
通過添加queryParamMap: of(params)和RouterTestingModule更正了單元測驗:
import {of} from 'rxjs';
import {RouterTestingModule} from '@angular/router/testing';
const params = {
get: jest.fn()
};
describe('ContainerComponent', () => {
//...
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
RouterTestingModule,
NgMaterialModule,
],
providers: [
// ...
{
provide: ActivatedRoute,
useValue: {
queryParamMap: of(params),
snapshot: {
queryParams: {
type: 'placeholder',
},
},
// ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/518429.html
上一篇:使用cx_Oracle進行單元測驗時模擬cursor.execute()的結果
下一篇:訪問MATCHER中的私有成員
