簡體   English   中英

如何模擬非ng2模塊?

[英]How to mock non ng2 module?

我正在ng2項目中使用第3方模塊。 我希望能夠模擬該模塊以進行測試,但是該模塊本身並沒有注入我的服務中,僅在其中需要。

如何覆蓋此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)
        }));

});

您不能直接模擬用於測試的客戶端模塊,因為它在同一文件中是必需的。 您可以將Client包裝到單獨的Angular服務中,並將其作為依賴項注入:

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
        })
    );
});

也許將第3方模塊包裝在angular2服務中,然后將該服務注入SshService中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM