问题描述
限时送ChatGPT账号..我正在尝试模拟组件测试中的服务依赖项,该服务有一个我正在尝试模拟的行为主题属性.
I am trying to mock out a service dependency inside a component test, this service has a behaviour subject property which I'm trying to mock.
我的服务如下:
export class DatePickerService {
public date: moment.Moment;
public selectedDate: BehaviorSubject<moment.Moment> = new BehaviorSubject<moment.Moment>(moment());
public changeDate = (date: moment.Moment) => {
this.selectedDate.next(date);
}
}
然后在我的组件中订阅 selectedDate:
The selectedDate is then subscribed to in my component:
ngOnInit() {
this.datePickerService.selectedDate.subscribe((selectedDate) => {
// do stuff here...
}
}
在测试我的组件时,我使用 TestBed 方法并为日期选择器服务提供我自己的模拟:
When it comes to testing my component, I am using the TestBed approach and supplying my own mock for the date picker service:
const mockDatePickerService = {
selectedDate: jasmine.createSpy().and.returnValue(of(moment('01-01-2018', 'DD-MM-YYYY')))
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
HttpClient,
HttpHandler,
{ provide: DatePickerService, useValue: mockDatePickerService }
],
imports: [
TranslateModule.forRoot(),
RouterTestingModule
]
})
pileComponents();
}));
在尝试运行我的第一个测试时,我收到来自
On trying to run my first test, I get an error from the
TypeError: undefined is not a constructor (evaluating 'this.datePickerService.selectedDate.subscribe')
如果我在组件的 onInit
中注销我的服务的值,我确实看到了我的模拟:
If I log out the value of my service in the component's onInit
, I do see my mock:
LOG: Object{selectedDate: function () { ... }}
所以我不确定为什么我会看到这个未定义的错误,我想知道我是否使用了 jasmine 和 returnValue
以及 of
调用?
So I'm unsure why i am seeing this undefined error, I am wondering if its my use of jasmine and the returnValue
with the of
invocation?
有人有什么想法吗?
谢谢
推荐答案
如果我是你,我会使用与我的服务相同的对象,并随心所欲地控制它.
If I were you, I would use the same object as my service uses, and control it however I want.
这是一个例子:
const subjectMock = new BehaviorSubject<moment.Moment>(undefined),
const mockDatePickerService = {
selectedDate: subjectMock.asObservable()
};
现在,您按原样提供它,并且在您的测试中,您可以简单地执行此操作(这是一个示例,而不是您必须执行的测试):
Now, you provide it as you did, and in your tests, you can simply do this (this is an example, not a test you must do) :
it('changeDate should call subject.next', () => {
const value = 'Moment value here';
subjectMock
.pipe(filter(res => !!res))
.subscribe(res => expect(res).toEqual(value));
subjectMock.next(value);
});
这篇关于在组件测试规范中模拟 BehaviourSubject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论