【问题标题】:Angular - Unit testing Subject()?Angular - 单元测试主题()?
【发布时间】:2018-08-30 07:54:58
【问题描述】:

我有一个仅使用主题的 Angular 服务,但我不确定如何为其编写单元测试。

我看到了 [this thread][1],但我觉得它没有太大帮助。

我试图模拟next(),但我有点迷失了。

【问题讨论】:

    标签: javascript angular typescript testing karma-runner


    【解决方案1】:

    您应该监视service.serviceMsg 而不是service,因为next() 方法似乎在serviceMsg 主题上。

    it('should catch what is emitted', () => {
        const nextSpy = spyOn(service.serviceMsg, 'next');
        service.confirm(ACTION);
        expect(nextSpy).toHaveBeenCalled();
    });
    

    编辑:

    您还应该更改创建service 实例的方式。您在代码中显示的内容仅适用于 component 实例创建

    beforeEach(() => {
        TestBed.configureTestingModule({
          providers: [MessageService]
        });
        service = TestBed.get(MessageService); // get service instance
        httpMock = TestBed.get(HttpTestingController);
    });
    

    【讨论】:

    • 我明白你的意思。虽然我收到了错误:Error: Illegal state: Could not load the summary for directive MessageService.
    • @trichetriche - 你知道这个问题吗?
    • 您不能像fixture = TestBed.createComponent(MessageService); service = fixture.componentInstance; 这样创建service 实例。这仅适用于组件。相反,您应该这样做 service = TestBed.get(MessageService)
    • 啊太棒了!感谢您的帮助@Amit :-)
    • @physicsboy 如果你想通知我,它必须是我已经评论过的问题/答案,否则我不会收到通知!
    【解决方案2】:

    首先,您可以订阅您的 Subject 并在里面期望一些值,然后执行将发出该值的方法:

    it('should catch what is emitted', () => {
        service.serviceMsg.subscribe(msg => {
            expect(msg).toEqual(something);
        });
        service.confirm(value); // this should match what you expect above
    });
    

    【讨论】:

    • 这样做你依赖于Subject的实现,这不是单元测试应该做的。你应该像他试图做的那样嘲笑它。
    • 我相信这不是单元测试,因为它包括创建模块或注入等内容。确实会依赖Subject实现。
    猜你喜欢
    • 2017-12-20
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2012-10-14
    • 2016-12-15
    相关资源
    最近更新 更多