将方法添加到父范围,以在父范围的上下文中测试表达式的执行

时间:2019-07-02 11:44:59

标签: javascript angularjs jasmine

我想测试外部表达式是否会被调用。
但是我不能将功能添加到父作用域。我该怎么办?

存在哪些模式或方法?

为什么测试失败external expression should be calling

angular.module('app', [])
  .directive('testDir', testDir);

function testDir() {
  return {
    scope: {
      externalExpression: '&'
    },
    template: '<button on-click="externalExpression()">Call external expression</button>'
  }
}

describe('testDir', () => {
  let scope;
  let compile;
  let validHTML;

  function create() {
    var elem, compiledElem;
    elem = angular.element(validHTML);
    compiledElem = compile(elem)(scope);
    scope.$digest();

    return compiledElem;
  }
  beforeEach(module("app"));

  beforeEach(
    inject(function($compile, $rootScope) {
      scope = $rootScope.$new();
      compile = $compile;
    })
  );

  it("should be defined", () => {
    validHTML = "<test-dir></test-dir>";
    const element = create();
    expect(element.find('button').length).toBe(1);
  });

  it("external expression should be defined", () => {
    const spy = jasmine.createSpy('spy');
    scope.externalExpression = spy;
    expect(Object.keys(scope)).toContain('externalExpression');
  });

  it('external expression should be calling', () => {
    const spy = jasmine.createSpy('spy');
    scope.externalExpression = spy;
    validHTML = '<test-dir external-expression="externalExpression()"><test-div>';
   
    const element = create();

    expect(Object.keys(angular.element(element.find('button')).scope())).toContain('externalExpression');
    element.find('button').triggerHandler('click');
    expect(scope.externalExpression.calls.count()).toBe(1);
  });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.1.0/jasmine.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/3.1.0/jasmine.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/3.1.0/jasmine-html.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/3.1.0/boot.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-mocks.js"></script>

1 个答案:

答案 0 :(得分:1)

on-click="externalExpression()"

更改为ng单击