我正在努力在 Angular 项目中测试服务。该服务非常小,但我不知道如何在课堂上测试观察者。
我正在尝试测试此类的方法。公共方法必须做它承诺做的事情。当我调用 'pop' 方法时,测试失败。由于 pop 方法是公共的,并且有一个 Message 作为返回值,因此该方法在调用后应该返回一条消息。在测试的情况下,底层代码不太相关。
测试失败的原因是此时观察者仍未定义。我认为是因为我在测试中调用pop方法的那一刻没有执行回调方法,所以addMessage观察者还没有初始化。
由于我刚刚开始这个项目,我对代码的假设持谨慎态度。有人对我如何测试此代码有建议吗?
pop 方法是公共的还是应该是私有的?
编辑:pop 方法被其他一些不能私有的类使用。我的问题实际上是:此服务的这种实现是否正确?
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { share} from 'rxjs/operators';
import { Observer } from 'rxjs';
import { Message } from 'primeng/components/common/api';
@Injectable()
export class FeedBackService {
obsAddMessage: Observable;
obsClearMessages: Observable;
/** @internal */
private clearMessages: Observer;
private addMessage: Observer;
/**
* Creates an instance of FeedBackService.
*/
constructor() {
this.obsAddMessage = new Observable(observer => this.addMessage = observer).pipe(share());
this.obsClearMessages = new Observable(observer => this.clearMessages = observer).pipe(share());
}
/**
* Synchronously create and show a new message instance.
*
* @param {(string | Message)} type The type of the message, or a Message object.
* @param {string=} title The message title.
* @param {string=} body The message body.
* @returns {Message}
* The newly created Message instance.
*/
pop( type: string | Message, title?: string, body?: string ): Message {
const message: any = typeof type === 'string' ? {severity: type, summary: title, detail: body} : type;
if (!this.addMessage) {
throw new Error('No Containers have been initialized to receive messages.');
} else {
this.addMessage.next(message);
}
return message;
}
}
考试:
从'primeng/components/common/api'导入{Message}; 从'./feedback.service'导入{FeedBackService}; fdescribe('Service: Feedback', () => { let feedbackService: FeedBackService; const MESSAGE: Message = {severity: 'This is a message', summary: 'Title', detail: 'Body'}; const SEVERITY = '严重性'; constSUMMARY = 'summary'; const DETAIL = 'detail'; beforeEach(() => { feedbackService = new FeedBackService(); }); it('#pop在传入消息时应该返回消息', () => { let returnMessage = feedbackService.pop(MESSAGE); }); });
错误:
像任何 Observable 一样,obsAddMessage
在订阅之前不会执行,因此正如您所展示的,如果您在订阅之前尝试推送新值,则观察者仍然未定义。解决方案只是在调用之前设置订阅feedbackService.pop()
。
我设置了一个简单的Stackblitz来展示我的意思。Stackblitz 的规范是:
it('#pop should return the message when passing in a message', () => {
feedbackService.obsAddMessage.subscribe(message => console.log(message));
let returnMessage = feedbackService.pop(MESSAGE);
expect(returnMessage).toEqual(MESSAGE);
});
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句