我真的是单元测试的新手,尤其是Angular。我有一个问题,在我的TestBed.configureTestingModule
中,我有一个提供程序,该提供程序具有私有getter,并且此getter依赖于自定义的通用服务,该服务从文件获取值。我如何模拟该值,而不必依赖搜索特定文件的自定义服务?可以说吸气剂是url
。我已经尝试过
{
provide: SomeService, useValue: {
url: 'www.test.com'
}
},
但是随后我的组件this.someService.SomeFunction is not a function
中出现错误,我缺少什么?
答案 0 :(得分:0)
假设提供者是服务,则一种优雅的方法是使用茉莉花工具spyOnProperty。
在您有私人获取者的地方这样的事情
@Injectable()
export class TestService {
private _url: string = 'www.random.com';
constructor() { }
private get url(): string {
return this._url;
}
}
并以此进行测试
describe('TestService', () => {
let testService: TestService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ ],
providers: [ TestService ]
});
testService = TestBed.get(TestService);
});
it('tests getter with property Spy', () => {
expect(testService.url).toEqual('www.random.com');
const urlSpy = spyOnProperty(testService, 'url', 'get').and.returnValue('www.happy.com');
expect(testService.url).toEqual('www.happy.com');
});
});