Проверка локальной переменной во время модульного тестирования на компоненте в Angular дает ошибку - PullRequest
1 голос
/ 12 апреля 2020

Предположим, есть 2 компонента: AppComponent и TestComponent. Я звоню в TestComponent, используя его директиву в шаблоне HTML AppComponent. Теперь TestComponent имеет свойство @Input () (пусть это будет myTitle).

Я занимаюсь модульным тестированием только для TestComponent. Для заголовка я передаю случайное значение в самом тесте. Вот код для того же:

app.component. html

<span><app-test [myTitle]="title"></app-test></span>

app.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = {name: 'hello-world'};
}

test.component. html

<p>test works!!{{myTitle.name}}</p>
<button (click)="onClick()">Click Please !!!</button>

test.component.ts

@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit{
    @Input() myTitle;
    filter;
    constructor(){

    }

    ngOnInit():void{
        this.myTitle.name = "Hi!!";
    }
    onClick(){
       this.filter="GokuSSj3";
    }
}

test.component.spe c .ts

describe('Test component',() =>{
    let temp;
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(async(() =>{
       TestBed.configureTestingModule({
           declarations: [TestComponent],
           schemas: [NO_ERRORS_SCHEMA]
       }) 
       .compileComponents();
    }));

    beforeEach(()=>{
        temp = {name: "Heloooo"};
       fixture = TestBed.createComponent(TestComponent);
       component = fixture.componentInstance;
    });

    it('should check First',()=>{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });

    it('should check whether onClick is called on button click or not and also the value of filter',()=>{
       component.myTitle = temp;
       spyOn(component,'onClick');
       fixture.detectChanges();

       let btn = fixture.debugElement.query(By.css('button'));
       btn.triggerEventHandler('click',null);

       fixture.whenStable().then(()=>{
          expect(component.onClick).toHaveBeenCalled();
          expect(component.filter).toEqual("GokuSSj3");
    });
});

Второй тестовый пример показывает ошибку : Ожидается, что неопределенное значение равно GokuSSj3. Почему это так? Несмотря на то, что был вызван onClick.

Я новичок в этом сообществе, поэтому, пожалуйста, помогите мне улучшить вопрос, если есть какие-либо ошибки.

1 Ответ

2 голосов
/ 13 апреля 2020

Поскольку вы добавили шпион на функцию onClick, она никогда не сработает и не обновит значение фильтра.

Вам необходимо удалить эту функцию шпиона и увидеть фактическое изменение значения.

Изменить тест как показано ниже:

it('should check whether onClick is called on button click or not and also the value of filter', () => {
      component.myTitle = temp;
      fixture.detectChanges();

      let btn = fixture.debugElement.query(By.css('button'));
      btn.triggerEventHandler('click', null);

      fixture.whenStable().then(() => {
        expect(component.filter).toEqual("GokuSSj3");
      });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...