Как создать данные-заглушки для данных входа пользователя

#angular #jasmine #karma-jasmine

#angular #jasmine #карма-жасмин

Вопрос:

Я пытался создать данные-заглушки для UserDetailsService .

Итак, я создал один объект-шпион, который я также использовал в провайдере.

Вот мой код

 beforeEach(async (() => {
  const mockUserDetailService = jasmine.createSpyObj('UserDetailsService',
    ['getUserRolePrivilegesByScreen']);
  TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule, MatDialogModule, BrowserAnimationsModule, RouterTestingModule, 
        MatMenuModule, MatFormFieldModule, MatInputModule, MatPaginatorModule, MatTableModule, 
        MatSortModule, MatIconModule, MatCardModule
      ],
      declarations: [DashboardComponent],
      providers: [
        { provide: DataService, useValue: spyDataService },
        { provide: UserDetailsService, useValue: mockUserDetailService},
        { provide: MAT_DIALOG_DATA, useValue: {} },
        { provide: MatDialogRef, useValue: {} },
        { provide: LayoutUtilsService, useValue: {} }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    .compileComponents();
}));
  

Я получаю эту ошибку

Ошибка типа: не удается прочитать свойство ‘CanRead’ неопределенного

Вот мой ts код, который находится в разделе ngOnInit

 this.dataService.setNumber(null);
if (this.userdetailservice.getUserHighestRole() == null) {
  this.router.navigateByUrl('login');
} else {
  this.screenPrivilege = this.userdetailservice.getUserRolePrivilegesByScreen('Damp;B');
  this.userRole = this.userdetailservice.getUserHighestRole();

  if (this.userRole == 'Fin' || this.userRole == 'Super') {
    this.columnToDisplay = [...this.Fin];
    this.landingPage = 'Fin';
    this.exportHeaders = ['No', 'Numb', 'Amout', 'Date', 'Salary', 'Status'];
  } else if (this.userRole == 'Gen') {
    this.columnToDisplay = [...this.Gen];
    this.landingPage = 'Gen';
    this.exportHeaders = ['No', 'Numb', 'Amout', 'Date', 'Salary', 'Status'];
  } else {
    this.landingPage = 'Admin';
    this.columnToDisplay = [...this.Admin];        
    this.exportHeaders = ['No', 'Numb', 'Amout', 'Date', 'Salary', 'Status'];
  }

  if (this.screenPrivilege.canRead == 'Y') {
    this.loadData();
    this.loadPeriod();
  }
}
  

Ответ №1:

Из предоставленного вами фрагмента кажется, что вы создали фиктивную переменную:

 const mockUserDetailService = jasmine.createSpyObj(...);
  

Но макет ничего не возвращает. Возможно, что-то вроде этого:

 mockUserDetailService.getUserRolePrivilegesByScreen.and.returnValue({canRead: 'Y'});