Ошибка Жасмин: тест не пройден, хотя logi c реализован для удовлетворения условия - PullRequest
0 голосов
/ 31 января 2020

Я пишу angular тест, который сравнивает длину двух строковых массивов на основе условия. Я получаю ошибку:

Ошибка: ожидается, что 0 будет равно 6, даже если я выполняю условие.

Если вы видите в моем тестовом коде, я инициализирую idDocument объект.

Я пытаюсь проверить этот код

acceptedFileTypes = this.idDocument === undefined ? [] : AcceptedFileTypes;

TestComponent

describe('IdUploadComponent', () => {
  let component: IdUploadComponent;
  let fixture: ComponentFixture<IdUploadComponent>;
  let injector: TestBed;
  let messageService: MessageService;
  let messageServiceSpy: jasmine.Spy;
   const event = { file: {name : 'Test'} };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [IbaModule, NgxsModule.forRoot([]), HttpClientModule, HttpClientTestingModule],
      providers: [
        { provide: AppConfigService, useClass: MockAppConfigService },
        { provide: MessageService, useClass: MockMessageService },
        { provide: AuthenticationService, useClass: MockAuthenticationService }
      ]
    }).compileComponents();

    injector = getTestBed();
    messageService = injector.get(MessageService);
    messageServiceSpy = spyOn(messageService, 'add').and.callThrough();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(IdUploadComponent);
    component = fixture.componentInstance;
    component.fileUpload = () => undefined;
    component.idDocument = new IdDocument();
    fixture.detectChanges();
  });



  it('calls messageService on upload success', () => {
    component.fileUploaded(event);

    expect(messageServiceSpy).toHaveBeenCalled();
  });

  fit('sets the fileupload to be able to upload specific files types', () => {
   const expectedResult = [ '.pdf','.heic','.jpeg','.jpg','.png','.webp'];

   component.idDocument = new IdDocument({birthCountry: 23, hasDocument: true, birthCountryRequired: true, issuedCountry: 23, required: true, uploaded: true});
   fixture.detectChanges();

    expect(component.acceptedFileTypes.length).toEqual(expectedResult.length);
  });
});

Компонент

export class IdUploadComponent implements OnInit {

  value: any[] = [];
  uploadUrl: string;
  componentReady = false;
  public uploading: boolean;

  @Input() documentType = '';
  @Input() section: string;
  @Input() header: string;
  @Input() userId: string;
  @Input() idDocument: IdDocument;
  @Output() fileUploadEvent = new EventEmitter<string>();
  @Input() fileUpload: Function = noop;

  authHeader = {
    authorization: undefined,
    document: undefined
  };
  acceptedFileTypes = this.idDocument === undefined ? [] : AcceptedFileTypes;
  accept =  this.idDocument === undefined ? '' : AcceptedFileTypes.join(',');

  readonly maxFileSize = 10485760;

  constructor(
    private messageService: MessageService,
    private authenticationService: AuthenticationService,
    private appConfigService: AppConfigService
  ) {}

  ngOnInit() {
    this.authHeader.document = this.documentType;
    this.uploadUrl = this.appConfigService.appSettings.apiServer.identification + this.section
                                                                                  + '/'
                                                                                  + this.userId
                                                                                  + '/UploadIdentification';
    this.authenticationService.getAuthenticationToken().then(r => {
      this.authHeader.authorization = 'Bearer ' + r;
      this.componentReady = true;
    });


  }

}

Может кто-нибудь сказать мне, в чем проблема ??

1 Ответ

0 голосов
/ 31 января 2020

Во втором beforeEach вы устанавливаете component.idDocument = new IdDocument();, таким образом, это не undefined, это хорошо. Но когда этот компонент создается, для строки acceptedFileTypes = this.idDocument === undefined ? [] : AcceptedFileTypes; я считаю, что this.idDocument не определено в данный момент времени. Значения @Input() заполняются в ngOnInit. Даже если вы сделаете console.log(this.idDocument) в конструкторе, вы получите неопределенное значение.

Так что, чтобы это исправить, попробуйте сделать следующее в вашем компоненте:

 acceptedFileTypes: any; // You can put the type here as you wish
 accept: any; // You can put the types here as you wish

 ngOnInit() {
  this.acceptedFileTypes = this.idDocument === undefined ? [] : AcceptedFileTypes;
  this.accept = this.idDocument === undefined ? ''
 : AcceptedFileTypes.join(',');
 }

Кроме того, в вашем тесте это имеет fit, вы меняете component.idDocument в самом тесте. Это слишком поздно (this.acceptedFileTypes = ... привязка в ngOnInit не будет обновляться), правильное место для инициализации @Input() находится во втором beforeEach, как у вас.

Если вы хотите реагировать на изменения @Input(), извлечение хука жизненного цикла ngOnChanges().

================================== == Чтобы проверить неопределенное условие, к сожалению, вам нужно сделать что-то вроде этого.

describe('IdUploadComponent', () => {
  //.... same thing as before, initialize and compile your component
  beforeEach(async(() => )

  describe('idDocument defined', () => {
    beforeEach(() => {
      fixture = TestBed.createComponent(IdUploadComponent);
      component = fixture.componentInstance;
      component.fileUpload = () => undefined;
      component.idDocument = new IdDocument();
      fixture.detectChanges();
    });
    // your it tests with idDocument being defined can go here
 });
  describe('idDocument undefined', () => {
    beforeEach(() => {
      fixture = TestBed.createComponent(IdUploadComponent);
      component = fixture.componentInstance;
      component.fileUpload = () => undefined;
      component.idDocument = undefined;
      fixture.detectChanges();
    });
    // your it tests where idDocument is undefined can go here.
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...