简体   繁体   English

如何模拟非ng2模块?

[英]How to mock non ng2 module?

I'm working with a 3rd party module in my ng2 project. 我正在ng2项目中使用第3方模块。 I want to be able to mock this module for testing, but the module itself doesn't get injected into my service, it's just required in. 我希望能够模拟该模块以进行测试,但是该模块本身并没有注入我的服务中,仅在其中需要。

How do I overwrite this Client so that my test isn't using the actual module? 如何覆盖此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)
        }));

});

You can't directly mock Client module for the test since it's required in the same file. 您不能直接模拟用于测试的客户端模块,因为它在同一文件中是必需的。 You could wrap the Client in to a separate Angular service and inject that as a dependency: 您可以将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