angular - 正在调用的 spy 返回未通过 angular5 单元测试调用

标签 angular unit-testing spy

我的组件有:

export class JsonformComponent implements OnInit {
  @Input() dataplanDetails: any;
  public layout: any = [];
  public schema: any = {};

  ngOnInit() {
    this.dataplanDetails.subscribe(res => {
      return this.parseSchema(res.details.submissionFileSchema)
    })
  }

  parseSchema(submissionFileSchema) {
    console.log('in parseSchema')
    const fileSchema = JSON.parse(submissionFileSchema)

我的测试是:

fdescribe('JsonformComponent', () => {
  let component: JsonformComponent;
  let fixture: ComponentFixture<JsonformComponent>;
  const mockObservable = new Subject();

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        {provide: Store, useClass: StoreStub}
      ],
      imports: [],
      declarations: [JsonformComponent]
    }).compileComponents();
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(JsonformComponent);
    component = fixture.componentInstance;
    component['dataplanDetails'] = mockObservable
    fixture.detectChanges();
  }));

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

  it('should trigger a parseSchema event', () => {
    mockObservable.next({"details": { "submissionFileSchema": `{"properties": true, "layout": [true]}`}})
    spyOn(component, 'parseSchema').and.returnValue(true);
    expect(component.parseSchema).toHaveBeenCalled();
  })

console.log 会触发,因此它肯定在 parseSchema 函数中。但测试失败,预期 spy parseSchema 已被调用。

最佳答案

您正在可观察者触发该代码后设置您的 spy 。将您的 spy 移动到您将数据推送到您的主题的上方。

it('should trigger a parseSchema event', () => {
    spyOn(component, 'parseSchema').and.returnValue(true);
    mockObservable.next({"details": { "submissionFileSchema": `{"properties": true, "layout": [true]}`}})
    expect(component.parseSchema).toHaveBeenCalled();
})

关于angular - 正在调用的 spy 返回未通过 angular5 单元测试调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739311/

相关文章:

Angular 2 Universal - 存储全局变量

unit-testing - 如何在单元测试中模拟CRM插件沙箱隔离模式?

python - 如何在 Django 中编写单元测试

node.js - 如何监视 node.js 中定义的变量

javascript - 为什么它传递 console.log 作为 Observble subscribe() 函数的参数?

angular - Ionic 4 Angular Back Button 到上一页而不是 root?

angular - 如何将组件导入 Angular 2 中的另一个根组件

java - 如何在maven中测试之前取消设置环境变量

java - Mockito 模拟一个方法,但将其参数用于模拟返回

angularjs - 如何监视也被属性引用的函数