AngularJS中的视图单元测试出现问题

时间:2019-05-25 21:54:52

标签: angularjs unit-testing

在对AngularJS组件测试进行一些研究时,我读到了关于{strong>视图单元测试的信息,如here所述。我已经尝试过这种方式:

组件

angular.module("recipeDetail").component("recipeSummary", {
  templateUrl:
    "modules/recipe-detail/recipe-summary/recipe-summary.template.html",
  bindings: { recipe: "<" },
  controller: function RecipeSummaryController() {}
});

模板

<h1 id="recipe-title">{{ $ctrl.recipe.title }}</h1>
<p>
  Steps:
</p>
<ul>
  <li ng-repeat="step in $ctrl.recipe.steps" class="recipe-summary-step">
    {{ step.text }}
  </li>
</ul>

测试

describe("recipeSummary ViewUnitTest", () => {
  let scope;
  let $compile;
  beforeEach(module("recipeDetail"));

  beforeEach(inject(($rootScope, _$compile_) => {
    scope = $rootScope.$new();
    $compile = _$compile_;
  }));

  it("should display the steps", () => {
    scope.recipe = recipe;
    let el = angular.element('<recipe-summary recipe="recipe"/>');
    el = $compile(el)(scope);
    scope.$digest();
    expect(el[0].querySelectorAll("p").length).toBe(1); // to make sure this whole thing is working 
    expect(el[0].querySelectorAll(".recipe-summary-step").length).toBe(3);
  });
});

两个断言都失败-第一个(p)检查我是否正确实施了测试,第二个(.recipe-summary-step)检查组件的实际功能。

更新

我不觉得自己很蠢。乔治指出,我实际上没有打电话 scope.$digest()

所以这样做之后,我遇到了新的错误/失败:

Chrome 74.0.3729 (Mac OS X 10.14.4) recipeSummary ViewUnitTest should display the steps FAILED
        Error: Unexpected request: GET modules/recipe-detail/recipe-summary/recipe-summary.template.html
        No more request expected
        error properties: Object({ $$passToExceptionHandler: true })
            at createFatalError (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1569:19)
            at $httpBackend (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1616:11)
            at sendReq (lib/angular/angular.js:13257:9)
            at serverRequest (lib/angular/angular.js:12998:16)
            at processQueue (lib/angular/angular.js:17914:37)
            at lib/angular/angular.js:17962:27
            at ChildScope.$digest (lib/angular/angular.js:19075:15)
            at UserContext.<anonymous> (modules/recipe-detail/recipe-summary/recipe-summary.component.spec.js:32:11)
            at <Jasmine>

显然,templateUrl是通过实际的get请求解决的,显然这是一个致命错误。那么我该如何使用这种技术呢?

0 个答案:

没有答案