Angular Karma单元测试等待Isempty发出价值

发布于 2025-01-31 12:10:43 字数 716 浏览 3 评论 0 原文

我有以下用于处理错误的代码:

              catchError((error) => {
                return statement ? EMPTY : otherValue;
              }),

我正在尝试为此编写一个单元测试。在这里我取得了成就。

  it('test description', fakeAsync(() => {
    let saved: boolean;
    action = new action({ data: 'some data'});
    action$.next(action);

    effects.save.pipe(isEmpty()).subscribe((data: boolean) => {
      console.log('data:', data);
      saved = data;
    });
    flush();

    console.log('saved:', saved);
    expect(saved).toBeTrue();
  }));

我的输出看起来像:

```
'saved:', undefined
'data:', true
Error: Expected undefined to be true.
```

如何改进这次测试?

I have following code for handling errors:

              catchError((error) => {
                return statement ? EMPTY : otherValue;
              }),

I am trying to write an unit test for this. Here what I have achieved.

  it('test description', fakeAsync(() => {
    let saved: boolean;
    action = new action({ data: 'some data'});
    action$.next(action);

    effects.save.pipe(isEmpty()).subscribe((data: boolean) => {
      console.log('data:', data);
      saved = data;
    });
    flush();

    console.log('saved:', saved);
    expect(saved).toBeTrue();
  }));

My output looks like:

```
'saved:', undefined
'data:', true
Error: Expected undefined to be true.
```

What can I improve to make this test pass?

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

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

发布评论

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

评论(1

给不了的爱 2025-02-07 12:10:43

您正在尝试同步访问异步值。您应该在异步处理程序内使用完成的函数(内部 subscribe())。

it('test description', done => {
  action = new action({ data: 'some data'});
  action$.next(action);

  effects.save.pipe(isEmpty()).subscribe((data: boolean) => {
    console.log('data:', data);
    expect(data).toBeTrue();
    done();
  });
});

You're trying to synchronously access asynchronous value. You should use a done function inside the async handler (inside subscribe()).

it('test description', done => {
  action = new action({ data: 'some data'});
  action$.next(action);

  effects.save.pipe(isEmpty()).subscribe((data: boolean) => {
    console.log('data:', data);
    expect(data).toBeTrue();
    done();
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文