0

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

});
Justin Young
  • 2,393
  • 3
  • 36
  • 62

2 Answers2

1

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
        })
    );
});
Aleksi
  • 520
  • 4
  • 10
0

Maybe wrap the 3rd party module in a angular2 service and inject that service in the SshService.

Florian F
  • 8,822
  • 4
  • 37
  • 50