【问题标题】:Angular Js: Simple unit test not workingAngular Js:简单的单元测试不起作用
【发布时间】:2015-10-13 08:56:52
【问题描述】:

情况:

我正在尝试为我的 Angular 应用程序设置单元测试。我创建了一个基本的测试角度应用程序并编写了一个简单的单元测试,但没有按预期工作。

应用程序:

var app = angular.module( 'myApp', [] );

app.controller('InitCtrl', function( $scope, Person ) 
{
    $scope.test_person = Person.Person("Tom");
})

app.factory('Person', function(){
    return {
        Person: function(name){
            this.name = name;
            console.log ( name );
        }
    }               
})

单元测试:

describe('Person', function () {

  var Person;
  beforeEach(module('myApp'));
  beforeEach(inject(function (_Person_) {
    Person = _Person_;
  }));

  describe('Constructor', function () {

    it('assigns a name', function () {
      expect(new Person('Ben')).to.have.property('name', 'Ben');
    });

  });

});

错误信息:

当我运行测试时,我得到了实际的错误消息:

PhantomJS 1.9.8 (Mac OS X 0.0.0) Person "before each" hook: workFn for "assigns a name" FAILED
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.4/$injector/nomod?p0=myApp

尝试:

我尝试过使用不同的语法:

var app = angular.module( 'myApp' );

但这并不能解决问题。

问题:

这个简单的测试有什么问题?
应用程序中缺少某些内容,或者测试中有问题?

谢谢!

【问题讨论】:

    标签: javascript angularjs unit-testing karma-runner


    【解决方案1】:

    很可能你没有在karma configuration file 中加载你的 app.js:

    module.exports = function(config) {
        config.set({
            basePath: '',    
            files: [
                '../../path/to/app.js',
             //...
    

    【讨论】:

    • 谢谢。它确实缺少这一点。我仍然收到错误,但至少运行测试:Person Constructor assigns a name FAILED TypeError: '[object Object]' is not a constructor (evaluating 'new Person('Ben')')
    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 2016-05-14
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多