angular 单元测试 多个指令 [...] 要求 new/isolated 作用域

angular unit test Multiple directives [...] asking for new/isolated scope on

运行 单元测试失败并显示以下内容:

Error: [$compile:multidir] Multiple directives [sendEmail, sendEmail] asking for new/isolated scope on: <send-email resolve="">

我的单元测试设置如下。它尝试在不同的测试中两次 $compile 组件。 it 块是相同的。但是第二次添加失败。

import angular from 'angular';
import 'angular-mocks';
import {sendEmail} from './send-email.js';

describe('component - sendEmail', () => {
    let $rootScope;
    let $compile;
    beforeEach(() => {
        angular
            .module('app')
            .component('sendEmail', sendEmail);
        angular.mock.module('app');

        inject(function(_$rootScope_, _$compile_) {
            $rootScope = _$rootScope_;
            $compile = _$compile_;
        });
    });

    it('...', () => {
        const element = $compile('<send-email resolve=""></send-email>')($rootScope);
        $rootScope.$digest();
        expect(element.find('.hp-send-email-container').length).toEqual(1);
    });

    // adding it will fail the test
    it('...', () => {
        const element = $compile('<send-email resolve=""></send-email>')($rootScope);
        $rootScope.$digest();
        expect(element.find('.hp-send-email-container').length).toEqual(1);
    });
});

到目前为止,我已经尝试过重置范围和销毁组件以及这些的任意组合。但它没有任何效果。

it('...', () => {
    // tried creating and using a new scope for $compile
    // const $scope = $rootScope.$new(true);
    const element = $compile('<send-email resolve=""></send-email>')($rootScope);
    $rootScope.$digest();
    expect(element.find('.hp-send-email-container').length).toEqual(1);

    // tried removing the element as well as destroying the scope
    // element.remove();
    // $scope.$destroy();
});

最后我想要实现的是使用不同的输入多次编译组件并查看输出。也许我完全错误地解决了这个问题。欢迎提出任何建议。

问题是 Angular 模块是持久的。不应在规范中修改现有模块。

可以有多个具有相同名称(选择器)的指令,component 是一个指令的语法糖(参见 )。这个

beforeEach(() => {
    angular
        .module('app')
        .component('sendEmail', sendEmail);

导致在每个测试中为 send-email 选择器向堆栈添加一个新指令。

所以这将导致第二次测试出现 $compile:multidir 错误,因为组件具有独立的作用域,并且每个具有新作用域的元素不能有多个指令。

estus的回答很有道理,不过我也找到了替代方案。我还没有阅读它的文档,不知道它为什么有效,所以如果你知道,请发表评论。

angular
   .module('app', [])
   .component('sendEmail', sendEmail);
angular.mock.module('app');

唯一的变化是向模块添加了空的依赖项列表。这允许在每个 it 块中调用 $compile。