[英]How to create a Karma/Jasmine unit tests to check Angular service that depend on other module
I have read a lot of articles and I still don't understand how to create it. 我已经阅读了很多文章,但我仍然不知道如何创建它。
There is a module (“A”) that has service (“B”) that has function (“C”). 有一个模块(“ A”)具有服务(“ B”)且具有功能(“ C”)。 The function is using another function (“E”) in other module(“D”).
该功能正在其他模块(“ D”)中使用另一个功能(“ E”)。 I want to test the behavior of the function (“C”), with different answers from function (“E”), [true, False, etc...]
我想测试功能(“ C”)的行为,并从功能(“ E”),[true,False等...]获得不同答案
Example: 例:
angular.module('A',[]) // or angular.module('A',['D']) .service('B', function(){ this.C = function() { return !DE() ; };
I built the app with Yeoman Angular generator 我使用Yeoman Angular生成器构建了该应用程序
Thank you 谢谢
Assuming everything lives under one module say A. 假设所有内容都在一个模块下,则说A。
angular.module('A',[])
.service('B', function(D) { // Using Dependency Injection we inject service D here
this.C = function() {
return !D.E();
}
return this;
})
.service('D', function() {
this.E = function() { return false; };
return this;
});
Unit Test: 单元测试:
describe('Unit Test for the Service B', function() {
var B, D;
beforeEach(function() {
module('A');
});
beforeEach(inject(function(_B_, _D_) {
B = _B_;
D = _D_;
}));
describe('Functionality of method C', function() {
it('should negate the returned value of the method E in service D', function() {
var E = D.E();
var C = B.C();
expect(E).toBeFalsy();
expect(C).toBeTruthy();
});
});
});
Lets say that it lives in a different module - module Z. 假设它位于另一个模块-模块Z中。
angular.module('A',['Z']) // Now we include the module Z here
.service('B', function(D) { // and again using Dependency Injection we can inject service D here.
this.C = function() {
return !D.E();
}
return this;
});
angular.module('Z', [])
.service('D', function() {
this.E = function() { return false; };
return this;
});
Unit Tests: 单元测试:
describe('Unit Test for the Service B', function() {
var B, D;
beforeEach(function() {
module('A');
module('Z');
});
beforeEach(inject(function(_B_, _D_) {
B = _B_;
D = _D_;
}));
describe('Functionality of method C', function() {
it('should negate the returned value of the method E in service D', function() {
var E = D.E();
var C = B.C();
expect(E).toBeFalsy();
expect(C).toBeTruthy();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.