在组件测试规范中模拟BehaviourSubject [英] Mocking a BehaviourSubject in a component test spec

查看:80
本文介绍了在组件测试规范中模拟BehaviourSubject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在组件测试中模拟出服务依赖关系,该服务具有我正在尝试模拟的行为主题属性.

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
        ]
    })
    .compileComponents();
}));

在尝试运行我的第一个测试时,我从

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 () { ... }}

所以我不确定为什么会看到这个未定义的错误,我想知道它是否与我使用茉莉花和returnValueof调用一起使用?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆