Jasmine/Karma: ошибка типа: this.role.toLowerCase не является функцией

#javascript #angular #typescript #jasmine #karma-jasmine

#javascript #угловой #typescript #jasmine #karma-jasmine

Вопрос:

Я работаю над написанием тестового примера для одной из страниц приложения, над которым работает наша команда. Но я столкнулся с ошибкой в одном тестовом примере, я не нахожу способ пройти мимо. Мой файл спецификации

 import { UserApiService } from 'src/app/services/api/user-apiservice';
import { MatDialog } from '@angular/material/dialog';
import { AuthenticationService } from '../../services/shared/authentication.service';

import { MainViewComponent } from './mainview.component';
import { of } from 'rxjs';

describe('MainViewComponent', () => {
  let component: MainViewComponent;
  let fixture: ComponentFixture<MainViewComponent>;
  let mockTlsApiService, mockMatDialog, mockAuthenticationService;

  beforeEach(async(() => {
    mockAuthenticationService = jasmine.createSpyObj(['getUserData','getDateData']);
    mockAuthenticationService.getUserRole = jasmine.createSpy().and.returnValue(of(['admin']));
    mockAuthenticationService.getUserRole.toLowerCase = jasmine.createSpy().and.returnValue(of(['admin']));
    mockAuthenticationService.getUserFullName = jasmine.createSpy().and.returnValue(of([]));

    TestBed.configureTestingModule({
      declarations: [ MainViewComponent ],
      providers: [
        {provide: UserApiService, useValue: mockTlsApiService},
        {provide: MatDialog, useValue: mockMatDialog},
        {provide: AuthenticationService, useValue: mockAuthenticationService},
      ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MainViewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
  

Код, который он тестирует, когда я получаю ошибку, таков

   constructor(    
    private repoService: UserApiService,
    public dialog: MatDialog,
    private authenticationService: AuthenticationService,
  ) {
   
  }
  ngAfterViewInit(): void {
  this.dataSource.sortingDataAccessor = (item, property) => {
    switch (property) {
       case 'origDate': return new Date(item.origDate);
       default: return item[property];
    }
  };
  }
  ngOnInit(): void {
    this.getQueues();

    this.getData();

    this.toolOrderNoFilterFunc(); this.toolNoFilterFunc(); this.eclFilterFunc(); this.abbrFilterFunc(); this.seriesFilterFunc(); this.nameFilterFunc(); this.toolTypeFilterFunc();
    this.toolChangeFilterFunc(); this.ccnDesFilterFunc(); this.ccnFabFilterFunc(); this.revFilterFunc();
  }
. . .
  getQueues(){
    this.role=this.authenticationService.getUserRole();
    this.allQueues = ['ME1', 'ME2', 'Est', 'Safe', 'TFab', 'Fin', 'Acct', 'Shop Stat','Rel']
    this.userFullName = this.authenticationService.getUserFullName();
    //is it Tfab or Tool???
    if(this.role.toLowerCase().search("admin") != -1 ){
        this.arrayQueues = ['ME1', 'ME2', 'Est', 'Safe', 'TFab', 'Fin', 'Acct', 'Shop Stat','Rel']
        //this.arrayQueues = ['TFab', 'Fin', 'ME1']
    } else {
      if(this.role.toLowerCase().search("me or designer") != -1 ){
          this.arrayQueues.push('ME1')
          this.arrayQueues.push('ME2')
      }
      if(this.role.toLowerCase().search("estimating") != -1 ){
        this.arrayQueues.push('Est')
      }
      if(this.role.toLowerCase().search("saftey") != -1 ){
        this.arrayQueues.push('Safe')  //is it SAF or Safe???
      }
      if(this.role.toLowerCase().search("tool fab") != -1 ){
        //is it Tfab or Tool???
        this.arrayQueues.push('TFab') 
      }
      if(this.role.toLowerCase().search("finance") != -1 ){
        this.arrayQueues.push('Fin')
      }
      if(this.role.toLowerCase().search("accountability") != -1 ){
        this.arrayQueues.push('Acct')
      }
      if(this.role.toLowerCase().search("read only") != -1 ){
        this.arrayQueues = this.allQueues
      }
    }

    this.isempty = false;
    // console.log(this.arrayQueues)
  }
  

Когда тест достигает первого this.role .toLowerCase(), я получаю ошибку, которая является заголовком этого сообщения.

Я попытался создать макет для роли и макет для toLowerCase, но они заканчиваются большим количеством ошибок. Я также пытался использовать spyOn.

Как я могу исправить это сообщение об ошибке?

Комментарии:

1. this.authenticationService.getUserRole() Всегда ли возвращается string 100% времени? Или он иногда возвращает что-то вроде null или undefined ? Если это так, то вам нужно что-то сделать для обработки этих случаев, потому что вы получите эту ошибку при вызове null.toLowerCase()

2. wind up with more errors ??? что это были за ошибки. Вы всегда должны имитировать службу как часть модульного тестирования. Если вы можете поделиться этими ошибками, мы поможем вам это исправить

3. В настоящее время я работаю над другими компонентами приложения. Я, вероятно, вернусь к этому позже сегодня. Что касается комментария Шашанка, я считаю, и, возможно, я ошибаюсь, та часть, где я создаю mockAuthenticationService, была имитацией сервиса. Возможно, мне, возможно, придется издеваться над ним по-другому для этого компонента, но для всех других компонентов в этом приложении этот способ издевательства сработал.

Ответ №1:

Итак, я изменил способ, которым я издевался над службой аутентификации с

 mockAuthenticationService = jasmine.createSpyObj(['getUserData','getDateData']);
mockAuthenticationService.getUserRole = jasmine.createSpy().and.returnValue(of(['admin']));
mockAuthenticationService.getUserRole.toLowerCase = jasmine.createSpy().and.returnValue(of(['admin']));
mockAuthenticationService.getUserFullName = jasmine.createSpy().and.returnValue(of([]));
  

к этому

 export class mockAuthentication{
  getUserRole(){
    return "admin";
  };
  getUserFullName(){
    return "Test User";
  }
};
  

и обновите инструкцию provide из

 {provide: AuthenticationService, useValue: mockAuthenticationService},
  

к этому

 {provide: AuthenticationService, useClass: mockAuthentication},
  

и мой тест сейчас проходит. Что через меня для цикла заключалось в том, что первый метод издевательства над сервисом работал в нескольких других компонентах в том же приложении.