如何修复单元测试中的错误 "is not a function" angular 11

how to fix an error "is not a function" in unit testing angular 11

我多次看到这个错误,但我的问题有任何解决方案,

我的组件:

*/
@Component({
  selector: 'ngx-modal-result-training',
  templateUrl: './modal-result-training.component.html',
  styleUrls: ['./modal-result-training.component.scss'],
})
export class ModalResultTrainingComponent implements OnInit {
  @Input() results: IAttempt;
  @Input() training: ITraining;
  public validated = false;
  public opinionForm: FormGroup;
  public selectedStars = 0;
  public hasAlreadyComment = true;
  public percentageScore: number;

  constructor(
    private opinionsService: OpinionsService,
    private userService: UserService,
    private ref: NbDialogRef<ModalResultTrainingComponent>,
    private router: Router,
    private toastrService: NbToastrService,
    private translateService: TranslateService,
    private dialogService: DialogService
  ) {}

  public ngOnInit(): void {
    this.dialogService.refs.push(this.ref);
    this.percentageScore = Math.floor(this.results.score);
    this.validated = this.percentageScore >= this.training.minimalScore;

    this.checkUserOpinion();
    this.initForm();
  }

我的测试:


const training = {
  id: 'ZGtz6yrEemCNTo5KAytu',
  refProject: 'JGvD1faO8L2vWb66BQ87',
  publicationDate: new Date(),
  version: 1,
  name: 'My project',
  groups: [],
  category: '',
  description: '',
  minimalScore: 80,
  previewPNG: '',
  level: 5,
  gain: 5,
  fromDate: new Date(),
  toDate: new Date(),
  totalSlides: 20,
  stars: 3,
  averageStars: 4,
  comments: 15,
  groupsHistoric: [],
} as ITraining;

const trainingResults = {
  id: 'ZDqzqg',
  version: 1,
  trainingID: 'xSOvDC6vpZTzVqXy5owQ',
  userID: 'qdZDZDqg',
  groupsIDs: [],
  date: new Date(),
  time: 10,
  score: 10,
  validated: true,
  finished: true,
  currentStep: 4,
} as IAttempt;

fdescribe('ModalResultTrainingComponent', () => {
  let component: ModalResultTrainingComponent;
  let fixture: ComponentFixture<ModalResultTrainingComponent>;
  let mockOpinionsService =  jasmine.createSpyObj('OpinionService', ['addOpinion']);
  let mockDialogService = jasmine.createSpyObj('DialogService', ['closeAll', 'refs', 'push']);
  let mockUserService = jasmine.createSpyObj('UserService', ['user$']);
  let mockRouter = jasmine.createSpyObj('Router', ['navigate']);
  let mockToastrService = jasmine.createSpyObj('NbToastrService ', ['success']);
  let mockTranslateService = jasmine.createSpyObj('TranslateService ', ['instant']);
  let nbAclService = jasmine.createSpyObj('NbAclService' , ['allow', 'can', 'register', 'setAccessControl']);
  let nbDialogRef = jasmine.createSpyObj('NbDialogRef', ['push']);

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ModalResultTrainingComponent],
      providers: [
        {provide :  Router, useValue: mockRouter},
        {provide :  OpinionsService, useValue: mockOpinionsService},
        {provide :  UserService, useValue: mockUserService},
        {provide :  DialogService, useValue: mockDialogService},
        {provide :  NbToastrService, useValue: mockToastrService},
        {provide :  TranslateService, useValue: mockTranslateService},
        {provide :  NbDialogRef, useValue: nbDialogRef},
        EntityService,
        {provide : NbAclService, useValue : nbAclService},
        ],
      imports: [
        FireModule,
        RouterModule.forRoot([]),
        NbThemeModule.forRoot(),
        NbDialogModule.forRoot(),
        NbAuthModule.forRoot(),
        TranslateModule.forRoot(),
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ModalResultTrainingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    mockOpinionsService = TestBed.inject(OpinionsService);
    mockUserService = TestBed.inject(UserService);
    mockDialogService = TestBed.inject(DialogService);
    mockRouter = TestBed.inject(Router);
    mockToastrService = TestBed.inject(NbToastrService);
    mockTranslateService = TestBed.inject(TranslateService);
    nbAclService = TestBed.inject(NbAclService);
    nbDialogRef = TestBed.inject(NbDialogRef);
    component.training = training;
    component.results = trainingResults;


  });

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

我不明白为什么会出现此错误:“类型错误:this.dialogService.refs.push 不是函数”

我尝试替换 useClass 而不是 useValue 但我无法知道是 angular 11。 我做了很多研究,但我发现了什么。

感谢大家的帮助

当你这样做时:

let mockDialogService = jasmine.createSpyObj('DialogService', ['closeAll', 'refs', 'push']);

你说 DialogService 上有一个我想模拟的 refs 方法,但 refs 不是方法,它是一个实例变量。

要修复它,我会这样做:

let mockDialogService = jasmine.createSpyObj('DialogService', ['closeAll']);
mockDialogService.refs = [];

现在我们附加了一个 refs 属性 和一个空数组,希望您不会再看到该错误。我们分配了一个空数组,因此 .push 可以工作。