简体   繁体   中英

How to mock non ng2 module?

I'm working with a 3rd party module in my ng2 project. 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?

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:

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中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM