[英]Angular JS Unit testing: how to test function in service that doesn't return
I'm sorry for possible duplicate, I didn't find any solution for my problem. 很抱歉,可能会重复,但没有找到解决我问题的方法。
I'm need to write tests for a service in Angular JS app. 我需要在Angular JS应用中为服务编写测试。
So I have one main function that returns and uses as an external method. 因此,我有一个主要的函数可以返回并用作外部方法。 And a couple help functions for external.
还有一些外部帮助功能。 So how can I call and test things inside help functions (
subFunc
)? 那么,如何在帮助函数(
subFunc
)中调用和测试事物呢?
service.js service.js
function TestService() {
return {
mainFunc: mainFunc
};
funcion mainFunc() {
//do some and call subFunc()
subFunc(a)
}
function subFunc(a) {
if (a === 1) {
// ... magic 1
return true;
} else {
// ... magic 2
return false;
}
}
}
})()
service.spec.js service.spec.js
describe('Test Service', function() {
beforeEach(module('TestService'));
var TestService;
beforeEach(inject(function($injector) {
TestService = $injector.get('TestService');
}));
it('should return true if subFunc called with 1', function () {
// ....
});
})
Rewrite TestService to expose subFunc
so that you can stub it with a spy and track whether it was called. 重写TestService以公开
subFunc
以便您可以与间谍一起对其进行存根并跟踪其是否已被调用。
That is one of the reasons you write tests before and while writing the code: they will influence the style of the code so as to make it easier to test. 这就是您在编写代码之前和同时编写测试的原因之一:它们将影响代码的样式,从而使测试变得更加容易。 In this case
subFunc
has to be externally visible to allow easy testing so make it visible. 在这种情况下,
subFunc
必须在外部可见,以便于测试,因此使其可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.