简体   繁体   English

使用未触发订阅方法可观察到的角单元测试

[英]Angular unit tests observable with subscribe method not firing

How can I get this subscribe to fire in my unit tests. 我如何才能在单元测试中得到订阅。

.close.then((resolve: IModelInstance): void => {
    resolve.status$.subscribe((status: Status): void => {
      this._checkStatus(status);
    });
  });

the this._checkStatus(status) has some logic that checks value in order to fire the component's output. this._checkStatus(status)具有一些检查值的逻辑,以触发组件的输出。

Now so far in my unit tests, I have mocked the promise to return a resolve callback like so: 到目前为止,到目前为止,在单元测试中,我已经嘲笑了像下面这样返回promise回调的承诺:

......as Spy).and.returnValue({
  close: new Promise((resolve: Function): void => {
    closeResolve = resolve;
  })
});

The data to pass to closeResolve is a follows: 传递给closeResolve的数据如下:

        beforeEach(async(() => {

          closeResponseSubject = new Subject<Status>();

          closeResponse = {} as Partial<Instance> as Instance;

          closeResponse.status$ = closeResponseSubject.asObservable();

          closeResponseSubject.next(Status.CREATED);

          closeResolve(closeResponse);
        }));

On using this appraoch, in the component the tests do go into the "then" but not into the susbcribe. 使用此方法时,组件中的测试确实会进入“ then”,但不会进入抄袭。 I've looked at different questions and answers here but so far no luck. 我在这里查看了不同的问题和答案,但到目前为止还没有运气。 I just quite don't understand why the test won't go into the subscribe. 我只是不明白为什么测试不会进入订阅。 I don't know 我不知道

Failed to figure out why the subscribe never fires with this appraoch, so instead of doing this: 无法弄清楚为什么订阅永远不会用此方法触发,因此请不要这样做:

.close.then((resolve: IModelInstance): void => {
    resolve.status$.subscribe((status: Status): void => {
      this._checkStatus(status);
    });
  });

I used this implementation instead: 我改用此实现:

.close.then((resolve: IModelInstance): void => {
    this._checkStatus(resolve.status);
  });

Then in the unit test I have the following data mock - the promise mock stays the same: 然后在单元测试中,我有以下数据模拟-promise模拟保持不变:

closeResponse = {
  status: Status.CREATED
} as Partial<Instance> as Instance;

............................................... ...............................................

beforeEach(async(() => {
  closeResolve(closeResponse);
}));

By doing so I don't need to subscribe to status$ to get the value of the status model. 这样,我不需要订阅status $就可以获取状态模型的值。 I simply point to another property status which also has the value i'm interested. 我只是指向另一个具有我感兴趣的价值的财产状态。

Like @Antoniossss suggested: "The whole idea is to write testable code that can be tested by simple tests". 就像@Antoniossss建议的一样:“整个想法是编写可通过简单测试进行测试的可测试代码”。

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

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