【问题标题】:Jasmine test : Expected a SPY but got a Function errorJasmine 测试:预期为 SPY,但出现功能错误
【发布时间】:2020-01-07 19:33:09
【问题描述】:

我已经使用 Jasmine 编写了一个 Angular 组件测试并出现错误。我基本上想测试调用 ngOnchanges 时是否调用 loadPersonNotes

ComplianceNoteComponent should call getPersonNote FAILED
        Error: <toHaveBeenCalled> : Expected a spy, but got Function.
        Usage: expect(<spyObj>).toHaveBeenCalled()
            at <Jasmine>

我不知道它为什么抱怨

茉莉花测试

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { of, Observable } from 'rxjs';
import { configureTestSuite } from 'ng-bullet';
import { DxButtonModule } from 'devextreme-angular';
import { NgxPermissionsModule } from 'ngx-permissions';

import { SharedFontAwesomeModule } from '../../../../shared/shared-font-awesome.module';
import { UserService } from '../../../../shared/services/user.service';
import { ComplianceNoteComponent } from './compliance-note.component';
import { IPersonNote } from '../../../../shared/models/IPersonNote';
import { IUser } from '../../../../shared/models/IUser';
import { nameof } from '../../../../shared/helpers/nameof';



describe('ComplianceNoteComponent', () => {
  let component: ComplianceNoteComponent;
  let fixture: ComponentFixture<ComplianceNoteComponent>;

  const mockPersonNote = <IPersonNote>{
    authorId : 12,
    id : 1,
    personId : 101,
    note : 'This is a test note ',
    authorName: 'xys',
    createdBy: 'ABC',
    createdDate : new Date()
  };

  const mockUserService: UserService = <UserService>{
    getCurrentUser() {
      return <IUser>{ id: 1 };
    },
    getPersonNote(id: 1) { 
      return of ({}); }
  };

  configureTestSuite((() => {
    TestBed.configureTestingModule({
      imports: [DxButtonModule, SharedFontAwesomeModule, NgxPermissionsModule.forRoot()],
      declarations: [ComplianceNoteComponent],
      providers: [
        { provide: UserService, useValue: mockUserService }
      ]
    });
  }));

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ComplianceNoteComponent ]
    })
    .compileComponents();
  }));

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

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

  it('should call getPersonNote', () => {
    spyOn(mockUserService, 'getPersonNote').and.returnValue(of(mockPersonNote)).and.callThrough();
    component.ngOnChanges();
    expect(component.loadPersonNotes).toHaveBeenCalled();
  });

});

组件

import { UserService } from 'src/app/shared/services/user.service';
import { IPersonNote } from 'src/app/shared/models/IPersonNote';

@Component({
  selector: 'app-compliance-note',
  templateUrl: './compliance-note.component.html',
  styleUrls: ['./compliance-note.component.scss']
})
export class ComplianceNoteComponent implements OnChanges {
  @Input() id: number;
  public personNotes: IPersonNote;
  public isCurrentUser = false;

  constructor(  private userService: UserService) { }

  ngOnChanges() {
    this.loadPersonNotes();
  }


  loadPersonNotes() {
    this.isCurrentUser = this.id !== this.userService.getCurrentUser().id;
    this.userService.getPersonNote(this.id).subscribe((x: IPersonNote) => {
      this.personNotes = x;
    });
  }

}

用户服务

    public getPersonNote = (id: number): Observable<IPersonNote> =>
    this.http.get<IPersonNote>(`${this.baseUrl}person-note/${id}`)  


export interface IPersonNote {
    id: number;
    personId: number;
    note: string;
    authorId: number;
    authorName: string;
    createdBy: string;
    createdDate: Date;
}   

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    问题是以下expect 需要spy,但您提供了类方法component.loadPersonNotes

    expect(component.loadPersonNotes).toHaveBeenCalled();
    

    要完成这项工作,您需要在调用 component.ngOnChanges 之前在 component.loadPersonNotes 方法上创建一个间谍。

    spyOn(component, 'loadPersonNotes');
    component.ngOnChanges();
    expect(component.loadPersonNotes).toHaveBeenCalled();
    

    根据测试描述,您希望验证来自UserServicegetPersonNote 是否被调用。因此,您可能必须重新考虑您的expect

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 2014-09-13
      • 2016-06-17
      • 2018-06-11
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多