Karma test paste event

Discussão em 'Angular' iniciado por rel1x, Setembro 11, 2024.

  1. rel1x

    rel1x Guest

    I have a simple component that handle paste event into a form input.

    The form:

    this.searchForm = this.formBuilder.group({
    query: [ null, [Validators.required] ]
    });

    onPaste(event) {
    event.preventDefault();
    const formattedQuery = event.clipboardData.getData('text/plain')
    .split(/,?[\r\n\t]+\s?/)
    .join(', ')
    .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
    }


    Now I am trying to test that and it looks like this:

    it('should reformat pasted data', () => {
    const queryField = fixture.debugElement.query(By.css('input[type="search"]'));
    queryField.nativeElement.dispatchEvent(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '123\r123'
    }));
    fixture.detectChanges();
    expect(queryField.nativeElement.value).toBe('123, 123');
    // also tried expect(component.searchForm.get('query').value).toBe('123, 123');
    });


    But as a result i've got

    Expected '' to be '123, 123'


    If i do console.log(queryField.nativeElement) it shows the input, but why it doesn't handle new ClipboardEvent('paste') event?

    <input class="ng-untouched ng-pristine ng-invalid" formcontrolname="query" type="search" ng-reflect-name="query">


    Full component you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app/hello.component.ts

    What's wrong with my unit test?

    Continue reading...

Compartilhe esta Página