使用Object作为参数测试Angular指令

时间:2016-05-11 16:05:39

标签: angularjs karma-jasmine angular-directive

我想测试从viewmodel接收对象的指令。该指令按预期工作,但我无法编写测试。我认为它与传递的对象有关。其他使用简单值的指令测试工作正常。

<dire status="ctrl.myObject"></dire>

测试:

var compile, scope, directiveElem;

beforeEach(function () {
module('App');
inject(function ($compile, $rootScope) {
  compile = $compile;
  scope = $rootScope.$new();
  scope.myMock = {
    prop0: true,
    prop1: true
  };

  directiveElem = getCompiledElement();
});

});

function getCompiledElement() {
    var testDirective = '<dire status="' + scope.myMock + '"></dire>';
    var compiledElement = compile(testDirective)(scope);
    scope.$digest();
    return compiledElement;
  }

it('should have template', function () {
    var spanElement = directiveElem.find('dire');
    expect(spanElement).toBeDefined();
  });

测试失败,出现以下错误:

Directive: dire should have template FAILED
    Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object]] starting at [Object]].
    http://errors.angularjs.org/1.4.9/$parse/syntax?p0=Object&p1=is%20unexpected%2C%20expecting%20%5B%5D%5D&p2=9&p3=%5Bobject%20Object%5D&p4=Object%5D

我希望有人能支持我。感谢。

1 个答案:

答案 0 :(得分:0)

myMock已设置在编译期间包含的scope中,因此您可以非常简单地使用:

scope.myMock = {
    prop0: true,
    prop1: true
};
...
var testDirective = '<dire status="myMock"></dire>';
var compiledElement = compile(testDirective)(scope); <-- scope