2017-01-19 5 views
0

私はng2プロジェクトでサードパーティのモジュールを使用しています。このモジュールを模擬してテストすることができますが、モジュール自体は私のサービスに注入されません。非ng2モジュールを模擬する方法は?

このClientを私のテストでは使用しないで上書きします実際のモジュールですか?

import {Injectable} from '@angular/core'; 

var Client = require('ssh2').Client; 

@Injectable() 
export class SshService { 

    constructor(){ 
     //Should log "hello world" 
     Client.myFunc(); 
    } 
} 



import { TestBed, inject } from '@angular/core/testing'; 


describe('My Service',() => { 

    beforeEach(() => { 

     TestBed.configureTestingModule({ 
      providers: [ 

       SshService 
      ] 
     }); 

    }); 
    it('should work as expected', 
     inject([SshService], (sshService:SshService) => { 

      sshService.Client = { 
       myFunc:function(){ 
        console.log('hello world') 
       } 
      } 
      console.log(sshService.Client) 
     })); 

}); 

答えて

0

たぶんangular2サービスにサードパーティのモジュールをラップし、SshServiceにそのサービスを注入。

+0

どうしますか? –

+0

@JustinYoung同じ考え、別の実装:http://stackoverflow.com/a/37176929/3033053 – silencedmessage

1

クライアントモジュールを同じファイルに必要とするため、テスト用に直接モックすることはできません。別のAngularサービスにClientをラップして、依存関係として注入することができます:

import { Injectable } from '@angular/core'; 
import { TestBed, inject } from '@angular/core/testing'; 

let Ssh2 = require('ssh2'); 

@Injectable() 
export class Ssh2Client { 
    public client: any = Ssh2.Client; 
} 

@Injectable() 
export class Ssh2ClientMock { 
    // Mock your client here 
    public client: any = { 
     myFunc:() => { 
      console.log('hello world') 
     } 
    }; 
} 

@Injectable() 
export class SshService { 

    constructor(public client: Ssh2Client) { 
     client.myFunc(); 
    } 
} 

describe('My Service',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      providers: [ 
       SshService, 
       { provide: Ssh2Client, useClass: Ssh2ClientMock } 
      ] 
     }); 
    }); 

    it('should work as expected', 
     inject([SshService], (sshService: SshService) => { 
      sshService.client.myFunc() // Should print hello world to console 
     }) 
    ); 
}); 
関連する問題