如何测试该服务的方法未调用subject.next()

时间:2019-07-07 20:43:48

标签: angular unit-testing jasmine

想象一下,我有一个服务,该服务的方法可以或不能将下一个值发送给主题。像这样:

@Injectable()
export class MyService {
    public onChange: Subject<string> = new Subject();
    check(send: boolean) {
        if (send) {
            this.onChange.next('hey!');
        }
    }
}

我可以轻松地使用service.check(true)测试案件-只需订阅onChange,但是如何才能调用onChange.next()中的service.check(false)呢?

编辑 / my-service.spec.ts

import { TestBed } from '@angular/core/testing';
import { MyService } from './my-service.service';

describe('MyService', () => {
    let service: MyService;

    beforeEach(() => {
        TestBed.configureTestingModule({ providers: [MyService] });
        service = TestBed.get(MyService);
    });
    it('can load instance', () => {
        expect(service).toBeTruthy();
    });
    it('should send notification with check(true)', () => {
        service.onChange.subscribe(
            msg => expect(msg).toEqual('hey!'),
            fail
        );
        service.check(true);
    });
    it('should not send notification with check(false)', () => {
        // ???? how to check that this.onChange.next() was not called?
        service.check(false);
    });
});

0 个答案:

没有答案