如何使用 jasmine 测试服务中模拟函数的回调?

问题描述 投票:0回答:1

我在组件中使用的服务方法有一个回调作为第二个参数。当执行此回调时,它会返回一个分配给组件中变量的值。

我想模拟我的服务中的方法以进行单元测试,并在单元测试中断言该服务方法能够更新我的组件的变量。

export class AppComponent {
      title = 'sample-app';
      sampleValue: string = '';

      constructor(private dataService:DataService)
      {}
  
      getSampleValue()
      {
        this.dataService.fetchData('Sample Value',(response) => {
          this.sampleValue = response;
        });
      }
    }



    export class DataService {
      constructor() {}

      fetchData(inputData:string,callback:(outputData:string)=>void) {
        const output:string = inputData + ' from service';
        callback(output);
      }
    }



    describe('AppComponent', () => {
      let component: AppComponent;
      let fixture: ComponentFixture<AppComponent>;
      let mockDataService:jasmine.SpyObj<DataService>;

      beforeEach(() => {
    
        mockDataService = jasmine.createSpyObj('DataService', ['fetchData']);
    
        TestBed.configureTestingModule({
          imports: [RouterTestingModule],
          declarations: [AppComponent],
          providers: [{
             provide: DataService,
             useValue: mockDataService
          }]
        });

        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    
      });


      it(`should set sample value as 'Sample Value from service'`, () => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.componentInstance;
        mockDataService.fetchData('Sample Value', (response) => {
          app.sampleValue = response;
        })
        expect(app.sampleValue).toEqual('Sample Value from service');
      });

     });

angular jasmine karma-jasmine
1个回答
0
投票

回调函数很难处理。我建议使用 Promisesasync 函数 来代替:

export class DataService {
  async fetchData(inputData: string): Promise<string> {
    const output = await someAsyncAction(inputData);
    return output;
  }
}

export class AppComponent {
  sampleValue = '';
  constructor(private dataService: DataService) {}
  
  async getSampleValue() {
    const response = await this.dataService.fetchData('Sample Value');
    this.sampleValue = response;
  }
}

spies的帮助下,您可以更轻松地编写测试:

it(`should set sample value as 'Sample Value from service'`, async () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  spyOn(TestBed.inject(DataService), 'fetchData').and.resolveTo('Sample Value from service');
  await app.getSamleValue()
  expect(app.sampleValue).toEqual('Sample Value from service');
});
© www.soinside.com 2019 - 2024. All rights reserved.