如何测试角度2中的可观察量

时间:2017-02-06 16:44:47

标签: angularjs unit-testing rxjs angular2-observables

安装我的测试套件,但无法弄清楚如何测试依赖第三方模块从服务器上获取文件名的observable。

如何模拟一个observable,以便我可以测试我的openConnection()方法?我不想直接用间谍替换它,只是模拟一个可观察的。

  

ssh.service.ts

openConnection(): Observable<any> {
            this.Client = this.ssh.getClient();

            return Observable.create((obs: Observer<string>) => {
                let remotePathToList = '/home';
                var conn = this.Client;
                this.Client.on('ready', ()=>{
                    conn.sftp((err:any, sftp:any)=>{
                        if (err) throw err;
                        sftp.readdir(remotePathToList, (err:any, list:any)=>{
                            conn.end();
                            obs.next(list);
                            //obs.complete(); // required, otherwise your subscription would never close
                        })
                    })
                }).connect(this.connSettings);
            });
        }
  

ssh.spec.ts

    describe('SSH service', () => {
    let subject: SshService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                SshService
            ]
        });
    });

    beforeEach(inject([SshService], (sshService: SshService) => {
        subject = sshService;
    }));

    it('should mock an observable', () => {

        var res =   Observable.create((obs: Observer<string>) => {
            obs.next('hello');
        });
        expect(subject.openConnection()).toEqual(res);
    });
});

1 个答案:

答案 0 :(得分:0)

试试这个,它应该从SSH服务中“伪造”已解析的observable。

describe('SSH service', () => {
let fakeData = "Fake Data I want to return"

let fakeSSHService = {
    openConnection: () => Observable.of(fakeData)
}

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            { provide: SshService, useValue: fakeSSHService }
        ]
    });
});