【问题标题】:Unit test Jasmine issue "Failed: XMLHttpRequest is not defined" for Angular componentAngular 组件的单元测试 Jasmine 问题“失败:未定义 XMLHttpRequest”
【发布时间】:2020-03-22 21:27:24
【问题描述】:

Angular CLI 自动为一个组件创建了一个失败的单元测试,我有一个问题要修复它。

消息: 1) WkplAmFindTabsComponent 应该创建 信息: 失败:无法读取属性 'injector' of null"

“消息: TypeError: 无法读取属性 'getComponentFromError' of null"

当我添加了

TestBed.initTestEnvironment(BrowserDynamicTestingModule,
            platformBrowserDynamicTesting());

下一个失败是: "1) WkplAmFindTabsComponent 应该创建 信息: 失败:未定义 XMLHttpRequest”

我的组件使用来自构造函数的路由器和来自输入的服务的方法。

@Input() makeHref: (param: object) => string;
constructor(private router: Router) {}
ngOnInit(): void {
   this.url = this.router.routerState.snapshot.url;
}

我的组件单元测试:

    beforeEach(async(() => {
        TestBed.resetTestEnvironment();
        TestBed.initTestEnvironment(BrowserDynamicTestingModule,
            platformBrowserDynamicTesting());

        TestBed.configureTestingModule({
            declarations: [ WkplAmFindTabsComponent ]
        })
        .compileComponents();
    }));

    it('should create', () => {
        const fixture = TestBed.createComponent(WkplAmFindTabsComponent);
        const component = fixture.componentInstance;
        fixture.detectChanges();

        expect(component).toBeTruthy();
    });
});

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    由于您要注入router,我认为您需要导入它。这也是我第一次看到resetTestEnvironment()initTestEnvironment 但我会忽略它。

    试试:

      beforeEach(async(() => {
            TestBed.resetTestEnvironment();
            TestBed.initTestEnvironment(BrowserDynamicTestingModule,
                platformBrowserDynamicTesting());
    
            TestBed.configureTestingModule({
                imports: [RouterTestingModule], // add this line !!
                declarations: [ WkplAmFindTabsComponent ]
            })
            .compileComponents();
        }));
    
        it('should create', () => {
            const fixture = TestBed.createComponent(WkplAmFindTabsComponent);
            const component = fixture.componentInstance;
            fixture.detectChanges();
    
            expect(component).toBeTruthy();
        });
    });
    

    测试路由的好资源:https://codecraft.tv/courses/angular/unit-testing/routing/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2019-03-26
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多