繁体   English   中英

在返回茉莉花承诺的方法上运行测试用例

[英]run a test case on a method that returns a promise with jasmine

我正在为返回承诺的函数编写测试用例。

newItem: any;

  public getNewItem() {
    this.storage.get('newItem').then((response) => {
        if (response) {
           this.newItem = response
        } else {
            this.doReset();
        }

  }

当我运行测试时,所有 doReset 都被调用,原因是没有分配 newItem。 我如何设置新项目所以 doReset 不运行。

这是规范文件:

describe('ItemService', () => {
  let service: ItemService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule,RouterTestingModule, IonicStorageModule.forRoot()],
      providers: [
        {provide: AlertService}
        ],
    });
    service = TestBed.inject(ItemService);
  });

  it('should be current item', () => {
    service.newItem = {name: 'Daniel', photos: ['image1.jpg', 'image2.jpg']}
    spyOn(service,'getCurrentItem').and.callThrough();
  });


});

使用Jasmine编写异步测试有不同的方法。 在您的情况下,最简单的方法是使用async / await如下:

it('should be current item', async () => {

  // given
  const newItem = {name: 'Daniel', photos: ['image1.jpg', 'image2.jpg']};
  service.newItem = newItem;

  // when
  const item = await service.getNewItem();

  // then
  expect(item).toBe(newItem);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM