在具有主代码的返回函数内测试具有返回函数的角度服务驻留在内部返回函数上

时间:2017-06-21 09:56:22

标签: angular testing

我的模块和工厂是

var testappservice = angular.module('testappservicemodule',[])
testappservice.factory('testappService',function(){
    return function(){
        var add = function(){
            return 'added';
        }
        return function(){
            add : add
       }
    }
})

我的测试套件

describe('testappService factory Testcases', function() {
    var testappService;

    beforeEach(function () {
        angular.mock.module('testappservicemodule');
    });

    beforeEach(inject(function(_testappService_) {
        testappService = _testappService_;
    }));

    it('testappService should be defined', function() {
        expect(testappService).toBeDefined();
    });

    describe('Test cases related to .add()', function() {
        it('testappService.add should be defined', function() {
            expect(testappService.add).toBeDefined();
        });
    });
});

当我运行Karma时,它显示异常为

与.add()

相关的测试用例

✗应定义testappService.add

预定未定义的定义。

我已经为此搜索了一个解决方案,却找不到任何解决方案。我想知道如何测试这种服务。

1 个答案:

答案 0 :(得分:0)

要访问这种方法,我们可以使用

expect(testappService().add).toBeDefined();

所以最后我们的代码就像

describe('Test cases related to .add()', function() {
    it('testappService.add should be defined', function() {
        expect(testappService().add).toBeDefined();
    });
});