[英]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.