【问题标题】:Observable property not updating in test using Angular / Mocha使用 Angular / Mocha 在测试中未更新可观察属性
【发布时间】:2018-01-15 17:21:32
【问题描述】:

我正在测试我编写的加载本地 JSON 文件的组件,一切都很好并且运行良好,但我的测试并不顺利!在我的组件中,我有以下内容可以加载我在项目中使用的 JSON 列表:

public softwareList: Observable<any>;

public ngOnInit() {
    this.softwareList = this.http.get('path/to/software.json').map((res: any) => {
        const respJson = res.json();
        return respJson.about.dependencies.software;
    });
}

在我的测试中,我模拟了 JSON 和 http.get 调用的结果,一切看起来都不错 - 下面是我的测试代码...

// here's the mock...
const mockResponse = {
    about: {
      dependencies: {
        heading: 'Software Dependencies',
        explaination: 'Blah blah blah',
        software: [
          {
            name: 'Angular & Angular Material',
            url: 'https://github.com/angular'
          }
        ]
      }
    }
  };


// here's my test
it('should load the Software Dependencies list', async(() => {
    const instance = componentFixture.componentInstance;
    const spyHttpGet = sinon.spy(instance.http, 'get');

    instance.ngOnInit();

    expect(spyHttpGet.calledOnce).to.be.eq(true);
    expect(spyHttpGet.withArgs'path/to/software.json').calledOnce).to.be.eq(true);

    instance.softwareList.subscribe((res:any) => {
      console.log(res); // [Object{name: 'Angular & Angular Material', url: 'https://github.com/angular'}]
      expect(instance.softwareList).to.be.eq(mockResponse.about.dependencies.software);
    });
  }));

现在这里是最后的测试,订阅回调中的那个失败了。我收到以下错误

AssertionError: 预期 { Object (_isScalar,observers, ...) } 到 等于 [ 数组 (1) ]

从 console.log 我看到以下内容:

[Object{name: 'Angular & Angular Material', url: 'https://github.com/angular'}]

这就是我所期望的!这也是我期望instance.softwareList 的价值!我不明白为什么我的instance.softwareList 没有更新到subscribe 返回的值?我错过了什么,为什么不是instance.softwareList = [{name: 'Angular &amp; Angular Material', url: 'https://github.com/angular'}]

任何解释将不胜感激!

【问题讨论】:

    标签: angular unit-testing mocha.js observable


    【解决方案1】:

    你在你的 ngOnInit 中影响到软件列表的 observable:this.softwareList = this.http.get

    所以 softwareList 有一个可观察的签名:

    对象(_isScalar,观察者,...)

    为了通过你的测试,你可以断言 observable 的响应:

    expect(res).to.be.eq(mockResponse.about.dependencies.softwar‌​e);
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2023-01-24
      • 2015-11-30
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多