Угловой модульный тест: невозможно изменить значение свойства после нажатия DOM - PullRequest
0 голосов
/ 22 сентября 2018

Итак, я новичок в тестировании 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();

  }));
});

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>

1 Ответ

0 голосов
/ 22 сентября 2018

Когда вы создаете жасмин spy, тогда не забывайте вызывать callThrough, иначе исходная функция не будет вызвана.

let spy = spyOn(component, 'onSelect').and.callThrough();

...