javascript - Angular 单元测试 : unable to change property value after DOM click

标签 javascript angular angular-test

所以我是 Angular 测试的新手,我想测试我的属性 selectedHeroes 在我单击 DOM 中的按钮后是否发生了变化。我还测试了当我在测试中触发按钮单击时是否调用了方法 onSelect() 并且确实如此。

但是,当我测试 selectedHero 属性值现在是否真实时。它说它仍然是未定义的。你们能看出为什么吗?

测试文件

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();

  }));
});

组件.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 ,否则不会调用原函数。
let spy = spyOn(component, 'onSelect').and.callThrough();

关于javascript - Angular 单元测试 : unable to change property value after DOM click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457714/

相关文章:

angular - 测试在 Angular 7 中向 <body> 添加类

angular - 如何使用Angular的HttpTestingController检查是否已向同一API端点发出2个HTTP请求?

javascript - 在文本框中查找总行数

Angular2路由重定向与routeParams

javascript - 简单的基于jQTouch Form的产品选择器

asp.net-mvc - Angular2 http post 无法捕捉 Controller Action

Angular 循环依赖警告

Angular 6 - NullInjectorError : No provider for HttpClient in unit tests

javascript - 如果调用不是来自表单中的提交方法,则 Express 的渲染/重定向不起作用

javascript - 如何从 node.js 访问 dynamo db