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

发布于 2025-02-01 11:37:09 字数 878 浏览 3 评论 0原文

我正在为返回承诺的功能写一个测试用例。

newItem: any;

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

  }

当我运行测试时,所有doreset都被称为“ newitem的原因”。我如何设置新项目,以免运行。

这是规格文件:

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();
  });


});

I'm writing a test case for a function that returns a promise.

newItem: any;

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

  }

When i run the test all doReset get called the reason being newItem is not being assigned. How do i set new item so doReset doesn't run.

This is the spec file:

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();
  });


});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缘字诀 2025-02-08 11:37:09

有不同的方法来编写 asynchronous tests 带有jasmine。就您而言,最简单的方法是使用async/等待,如下:

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);
});

There exist different ways to write asynchronous tests with Jasmine. In your case, the easiest way would be to use async/await as follows:

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);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文