【问题标题】:Angular: Testing HTTP with MockBackend, is async() really required?Angular:使用 MockBackend 测试 HTTP,真的需要 async() 吗?
【发布时间】:2017-05-07 11:52:32
【问题描述】:

我正在使用MockBackend 来测试依赖于@angular/http 的代码。
网络上的所有示例都使用异步测试设置,如下所示:
thoughtram: Testing Services with Http in Angular

describe('getVideos()', () => {

  it('should return an Observable<Array<Video>>',
      async(inject([VideoService, MockBackend], (videoService, mockBackend) => {

      videoService.getVideos().subscribe((videos) => {
        expect(videos.length).toBe(4);
        expect(videos[0].name).toEqual('Video 0');
        expect(videos[1].name).toEqual('Video 1');
        expect(videos[2].name).toEqual('Video 2');
        expect(videos[3].name).toEqual('Video 3');

        expect("THIS TEST IS FALSE POSITIVE").toEqual(false); 
      });

      const mockResponse = {
        data: [
          { id: 0, name: 'Video 0' },
          { id: 1, name: 'Video 1' },
          { id: 2, name: 'Video 2' },
          { id: 3, name: 'Video 3' }
        ]
      };

      mockBackend.connections.subscribe((connection) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify(mockResponse)
        })));
      });
  })));
});

但是,我试过了,我很确定 MockBackend 完全同步执行:

describe('getVideos()', () => {

  it('should return an Observable<Array<Video>>',
    inject([VideoService, MockBackend], (videoService, mockBackend) => {

      const mockResponse = {
        data: [
          { id: 0, name: 'Video 0' },
          { id: 1, name: 'Video 1' },
          { id: 2, name: 'Video 2' },
          { id: 3, name: 'Video 3' },
        ]
      };

      mockBackend.connections.subscribe((connection) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify(mockResponse)
        })));
      });

      let videos;
      videoService.getVideos().subscribe(v => videos = v);

      // synchronous code!?
      expect(videos.length).toBe(4);
      expect(videos[0].name).toEqual('Video 0');
      expect(videos[1].name).toEqual('Video 1');
      expect(videos[2].name).toEqual('Video 2');
      expect(videos[3].name).toEqual('Video 3');
    }));
});

我在这里创建了一个关于 plunker 的完整示例: https://plnkr.co/edit/I3N9zL?p=preview

自从写了这些文章以来,一定有一些地方发生了变化。 有人可以指出我的重大变化吗?还是我错过了一个重要的事实?

【问题讨论】:

  • 更改通过的测试并让它们仍然通过不一定有用 - 如果您使用 async 进行 failing 测试并删除该调用会发生什么?它仍然失败吗?
  • 第一个例子基本上是错误的,expect("THIS TEST IS FALSE POSITIVE").toEqual(false); 永远不应该是绿色的。如果代码异步运行,它会起作用。但它不再(不再)。
  • 我建议 mockResponse 是同步的,但 MockConnection 似乎没有是同步的。我为每个测试添加了第二个测试(将其减少到 2 个视频,同步视频失败,异步通过。

标签: javascript angular typescript angular2-testing


【解决方案1】:

您的假设完全正确,MockConnection.mockRespond() 发出同步信号。在这个特定的测试中不需要async()

我是您在问题中提到的文章的作者,我已经相应地更新了它。

非常感谢您指出这一点!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2017-06-28
    • 2022-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多