Updating input html field from within an Angular 2 test

前端 未结 3 464
独厮守ぢ
独厮守ぢ 2020-12-02 16:51

I would like to change the value of an input field from within an Angular 2 unit test.



        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 17:35

    I also had trouble getting jonrsharpe's answer to work with Angular 2.4. I found that the calls to fixture.detectChanges() and fixture.whenStable() caused the form component to reset. It seems that some initialization function is still pending when the test starts. I solved this by adding extra calls to these methods before each test. Here is a snippet of my code:

    beforeEach(() => {
        TestBed.configureTestingModule({
            // ...etc...
        });
        fixture = TestBed.createComponent(LoginComponent);
        comp = fixture.componentInstance;
        usernameBox = fixture.debugElement.query(By.css('input[name="username"]'));
        passwordBox = fixture.debugElement.query(By.css('input[type="password"]'));
        loginButton = fixture.debugElement.query(By.css('.btn-primary'));
        formElement = fixture.debugElement.query(By.css('form'));
    });
    
    beforeEach(async(() => {
        // The magic sauce!!
        // Because this is in an async wrapper it will automatically wait
        // for the call to whenStable() to complete
        fixture.detectChanges();
        fixture.whenStable();
    }));
    
    function sendInput(inputElement: any, text: string) {
        inputElement.value = text;
        inputElement.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        return fixture.whenStable();
    }
    
    it('should log in correctly', async(() => {
    
        sendInput(usernameBox.nativeElement, 'User1')
        .then(() => {
            return sendInput(passwordBox.nativeElement, 'Password1')
        }).then(() => {
            formElement.triggerEventHandler('submit', null);
            fixture.detectChanges();
    
            let spinner = fixture.debugElement.query(By.css('img'));
            expect(Helper.isHidden(spinner)).toBeFalsy('Spinner should be visible');
    
            // ...etc...
        });
    }));
    

提交回复
热议问题