使用Jasmine和Karma测试非平凡的AngularJS应用程序

Sne*_*sta 1 testing unit-testing jasmine angularjs

我正在开发一个非平凡的应用程序,具有以下文件夹结构:

build (required files such as angular.js)
Gruntfile.js
karma.conf.js
logs/
node_modules/
src/
    - app/
        - app.js
        - module_name/
            - module.js
            - controllers/
                - controller1.js
                - controller2.js
            - views/
                - view1.html
    - assets/
        - 1.jpg
        - styler.css
    - components/   (plugged in modules [angular-ui, etc])
    - index.html
Run Code Online (Sandbox Code Playgroud)

我的控制器都附加到其父模块.然后在我的app.js文件中需要该模块.

我曾尝试编写一些单元测试,但我似乎一直遇到依赖性问题,因为我尝试测试的控制器需要它的模块,然后该模块需要另一个模块等.

我的问题有几个部分:

  1. 如何构建我的karma.conf.js文件以包含必要的文件?具体来说这部分配置:

    files: [
       'files_to_be_tested.js',
    ]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用Jasmine,如何使用所有正确的依赖项编写单元测试?例如,我运行以下测试

使用Javascript

using 'strict'
describe('my Module', function() {
    describe('myController', function() {
        var ctrl, scope;

        beforeEach(module('myModule'));

        beforeEach(inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            ctrl = $controller('myController', { $scope: scope });
        }));

        it('should work', function() {
            // Execute functionality
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

但我一直得到错误:Unknown provider: $stateProvider我认为这是来自加载模块的路由配置.

我开始怀疑我是否正确地分离出我的控制器?

con*_*ode 6

回答第二个问题:

Unknown provider: $stateProvider是由ui.router未加载模块引起的.要解决此问题,请添加beforeEach(module('ui.router'))

出现问题是因为您正在加载的控制器正在尝试注入 $state

确保ui.routerJavascript文件在files列表中,karma.conf.js否则模块将无法用于karma.