[英]Angular - How can I mock an external function in a unit test?
I'm trying to write an angular unit test for a function that has a dependency on an imported function - how can write a unit test that mocks the results of the imported function? 我拥有的 function 是:
import { DependentMethod } from './dependentMethod';
export function doSomething() {
const dependentResults = DependentMethod(); // DependentMethod makes an http call and returns the result
return dependentResults;
}
在这种情况下,我想测试doSomething
并模拟DependentMethod
function。 当我之前尝试模拟东西时,我在 class 方法上使用了spy
,但我不确定在这种情况下如何处理它。 任何帮助将不胜感激!
您可以尝试以下方法,
import { dependent } from './dependentLibrary';
describe('yourCoponent', () => {
let component: yourComponent;
let service : dependentService;
beforeEach(() => {
service = new dependent(null); // if your service has further dependency
component = new yourComponent(service);
});
it('should perform test', () => {
// Arrange part -->
spyOn(service, 'dependentMethod').and.callFake(() => {
return Observable.from([ [1,2,3] ]); // return your mock data
});
//Act part
component.ngOnInit();
//Assert
expect(component.testable.action).toBe(value);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.