这是我的部件。我有一张名叫movies的电影清单。我想测试电影的计数是否正确,是否使用角度测试。
import {AfterViewInit, ChangeDetectorRef, Component, EventEmitter, Injector, Input, OnInit, Output, ViewChild} from '@angular/core';
import {Select, Store} from '@ngxs/store';
import {Observable} from 'rxjs';
export interface News {
heading:string,
text:string
}
@Component({
selector: 'app-root',
template: `
<p>hello</p>
<h1>Welcome to angular-test!</h1>
<div class="movie" *ngFor="let movie of movies">{{movie.title}}</div>
`,
styleUrls: ['./app.component.scss']
})
export class AppComponent{
title="angular-test";
movies = [
{ title: 'Interstellar' },
{ title: 'The big Lebowski' },
{ title: 'Fences' }
]
}这里是我的测试:
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import {By} from '@angular/platform-browser';
describe('render', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should show all the movies', () => {
let fixture = TestBed.createComponent(AppComponent);
const movieElement = fixture.debugElement.queryAll(By.css('.movie'));
console.log(movieElement)//prints: []
expect(movieElement.length).toEqual(3);
});
});然而,当我使用ng test运行我的测试时,我得到:
Chrome 72.0.3626 (Windows 10.0.0) render should show all the movies FAILED
Expected 0 to equal 3.
at UserContext.<anonymous> (http://localhost:9876/src/app/app.component.spec.ts?:21:33)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/node_modules/zone.js/dist/zone.js?:391:1)
at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/node_modules/zone.js/dist/zone-testing.js?:289:1)
at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/node_modules/zone.js/dist/zone.js?:390:1)
Chrome 72.0.3626 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.355 secs / 0.339 secs)有人能给我建议吗?
注意:当我运行ng s时,我可以看到movies数组正确地呈现。
发布于 2019-03-25 12:36:40
发生此问题是因为组件检测没有应用于您的测试套件。要解决您的问题,需要在fixture.detectChanges();中调用beforeEach。
溶液
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import {By} from '@angular/platform-browser';
describe('render', () => {
let component: AppComponent ;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
],
declarations: [
AppComponent
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
})
it('should show all the movies', () => {
const movieElement = fixture.debugElement.queryAll(By.css('.movie'));
console.log(movieElement)//prints: []
expect(movieElement.length).toEqual(3);
});
}); 希望这能帮上忙!
https://stackoverflow.com/questions/55337583
复制相似问题