这是我的组成部分。我有一个名为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
数组正确呈现
答案 0 :(得分:0)
发生此问题的原因是您的测试套件中未应用组件检测。要解决您的问题,您需要在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);
});
});
希望这会有所帮助!