Я все еще новичок в 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 = "[email protected]";
// 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();
});
});
});
Однако это не работает, потому что два оператора expect в теле вызова функции then вызывают ошибку, в которой говорится, что атрибут disabled действительно истинен.
Я действительно огляделся, чтобы узнать, есть ли у меня способ решить эту проблему, включая другие вопросы StackOverflow как этот. Но, к сожалению, мне не повезло.
Первоначально я предполагал, что функция whenStable () и тело вызова функции then выполняются асинхронно, но я почти уверен, что ошибаюсь в этом.
Что я должен сделать?





Судя по всему, я старый глупый медведь.
Кто-то, с кем я работаю, просмотрел код и указал на то, чего я не знал: функция spyOn должна использоваться Только при тестировании вызовов функций изолированно с использованием фиктивных объектов. Я закомментировал это, и тестовый пример работает так, как должен.
Я думаю, что произошло то, что мой компонентный объект, который прикреплен к шаблону, является актуальным.