所以我是 Angular 测试的新手,我想测试在单击 DOM 中的按钮后我的属性 selectedHeroes 是否发生更改。我还测试了当我在测试中触发按钮单击时是否调用 onSelect() 方法,并且确实如此。
但是,当我测试 selectedHero 属性值现在是否为 true 时。它说它仍然是未定义的。你们能明白为什么吗?
测试文件
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let userService;
let el;
beforeEach(async(() => {
const userServiceSpy = jasmine.createSpyObj('UserService', ['getUserData']);
TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [{provide: UserService, useClass: MockUserService}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
userService = TestBed.get(UserService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should change selectedHeroes property after click', fakeAsync(() => {
fixture.detectChanges();
let spy = spyOn(component, 'onSelect');
el = fixture.debugElement.query(By.css('li')).nativeElement.click();
tick();
expect(component.onSelect).toHaveBeenCalled();
expect(component.selectedHero).toBeTruthy();
}));
});
Component.ts
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit{
selectedHero;
heroes = [{id: 1, name: 'superman'}, {id: 2, name: 'Iron man'}];
ngOnInit() {}
onSelect(hero) {
this.selectedHero = hero;
}
}
模板
<div *ngIf="selectedHero">...</div>
<ul class="heroes">
<li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
最佳答案
当你创建 jasmine spy
时,不要忘记调用 callThrough
,否则原来的函数将不会被调用。
让 spy = spy On(组件,'onSelect').and.callThrough();
关于javascript - Angular 单元测试: unable to change property value after DOM click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457714/