Я все еще новичок в Angular и его платформах тестирования, Jasmine и Karma.
Я застрял при тестировании кнопки, чтобы убедиться, что когда пользователь вводит правильную информацию, она всегда включена; в основном вызывая .toBeFalsy () слишком рано, прежде чем элемент управления группы форм активирует кнопку. Теперь я не могу поделиться тем, что мой код именно по конфиденциальным причинам, ни с полным описанием проблемы , но один публичный пример, который я могу привести, - это страница регистрации Trello, показанная здесь здесь .
Изначально форма пуста и кнопка «Создать новую учетную запись» отключена, и пользователь не может щелкнуть по ней, чтобы создать учетную запись. Когда пользователь вводит правильную информацию в эти три текстовых поля, кнопка активируется, чтобы позволить пользователю отправить запрос в бэкэнд Trello для регистрации учетной записи.
Допустим, я, например, разработчик в Trello, который хочет протестировать случай, когда кнопка активируется, когда пользователь вводит правильную информацию, используя Jasmine и Karma с компонентом Angular 5 в качестве моего компонента для макет, функциональность и внешний вид. Проблема, с которой я сталкиваюсь, - это время, в которое состояние кнопки «Создать новую учетную запись» было изменено, чтобы включить ее, потому что, по сути, я проверяю, чтобы убедиться, что при правильном заполнении формы эта кнопка активируется и кнопка. Утверждение toBeFalsy () проходит.
Мой код для этого тестового набора и набора тестов, в котором содержится этот пример, будет следующим в create-account.component.spec.ts. (при условии, что компонент, содержащий MVC для страницы учетной записи Trello, называется CreateAccountComponent, и что все свойства компонента объявлены в create-account.component.ts)
// Import all the required components for the test.
// Some are redundant for this case, but are useful for testing the whole frontend page anyway.
import { async, ComponentFixture, TestBed, getTestBed } from '@angular/core/testing';
import { CreateAccountComponent } from './create-account.component';
import { Validators, AbstractControl, ValidatorFn, Validator, FormsModule, FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpHeaders, HttpRequest, HttpResponse, HttpInterceptor, HTTP_INTERCEPTORS, HttpClient, HttpErrorResponse, HttpClientModule } from '@angular/common/http';
import { Router } from "@angular/router";
import { RouterTestingModule } from '@angular/router/testing';
import { By } from '@angular/platform-browser'
describe(‘Trello Create Account’, () => {
// Test unit fields
let createAccountPageComponent: CreateAccountComponent;
let createAccountPage: ComponentFixture< CreateAccountComponent >;
let rootElementOfComponent: any;
let root_Debug_Element_Of_Component: any;
// Create and set up the testing module.
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CreateAccountComponent],
imports: [ ReactiveFormsModule , HttpClientModule, RouterTestingModule ]
})
.compileComponents();
}));
// Before each test case, initialize the suite fields as needed.
beforeEach(() => {
createAccountPage = TestBed.createComponent(CreateAccountComponent);
createAccountPageComponent = createAccountPage.componentInstance;
createAccountPage.detectChanges();
rootElementOfComponent = createAccountPage.nativeElement;
rootDebugElementOfComponent = createAccountPage.debugElement;
});
it('should have the Create New Account when the form fields are valid, () => {
// Watch for the ngModelChange function call when the value of the password, e-mail address
// and name change.
spyOn(createAccountPageComponent, 'updateCreateNewAccount');
// Simulate the user entering their full name.
rootDebugElementOfComponent query(By.css('#fullNameField')).nativeElement.dispatchEvent(new Event('input'));
createAccountPageComponent.createAccountPageForm.get(‘fullName').markAsTouched();
createAccountPageComponent.accountFullName= "Anonymous Person";
// Simulate the user entering their e-mail address.
rootDebugElementOfComponent query(By.css('#emailAddressField')).nativeElement.dispatchEvent(new Event('input'));
createAccountPageComponent.createAccountPageForm.get(‘emailAddress').markAsTouched();
createAccountPageComponent accountEmailAddress = "anonymous@person.com";
// Simulate the user entering a password.
rootDebugElementOfComponent query(By.css('#passwordField')).nativeElement.dispatchEvent(new Event('input'));
createAccountPageComponent.createAccountPageForm.get(‘password’).markAsTouched();
createAccountPageComponent.accountPassword = "anonymous";
// Update the new account button and have the screenshot track for changes.
createAccountPageComponent.updateNewAccountButton();
createAccountPage.detectChanges();
// Once the changes are detected, test to see if the 'Create New Account' button is enabled.
createAccountPage.whenStable().then(() => {
expect(rootElementOfComponent.querySelector('#createNewAccountButton').disabled).toBeFalsy();
expect(rootDebugElementOfComponent.query(By.css('#createNewAccountButtonButton')).nativeElement.disabled).toBeFalsy();
});
});
});
Тем не менее, это не работает, потому что два оператора ожидающих в теле функции then вызывают вызовы ошибок, говорящие о том, что атрибут disabled на самом деле равен true.
Я оглянулся вокруг, чтобы узнать, есть ли для меня способ решить эту проблему, включая другие вопросы StackOverflow , например, этот . Но, к сожалению, мне не повезло.
Моим первоначальным предположением было бы то, что функция whenStable () и тело вызова функции then выполняются асинхронно, но я почти уверен, что ошибаюсь в этом.
Что я должен делать?