Javascript 如何在 Angular 2 中对指令进行单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36432407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:03:55  来源:igfitidea点击:

How to Unit Test a Directive In Angular 2?

javascriptangularjsunit-testingangularangular2-directives

提问by daniel.caspers

Problem:I would like to be able to unit test a directive in Angular 2 to make sure that it properly compiles.

问题:我希望能够对Angular 2 中的指令进行单元测试,以确保它正确编译。

In Angular 1, it was possible to use$compile(angular.element(myElement)service and call $scope.$digest()after that. I specifically want to be able to do this in unit tests so I could test that when Angular ends up running across <div my-attr-directive/>in the code that my-attr-directivecompiles.

在 Angular 1 中,可以使用$compile(angular.element(myElement)服务并$scope.$digest()在此之后调用。我特别希望能够在单元测试中做到这一点,这样我就可以测试当 Angular 最终<div my-attr-directive/>my-attr-directive编译代码中运行时。

Constraints:

约束:

回答by Wojciech Kwiatek

Testing compiled directive using TestBed

使用 TestBed 测试编译指令

Let's say you have a following directive:

假设您有以下指令:

@Directive({
  selector: '[my-directive]',
})
class MyDirective {
  public directiveProperty = 'hi!';
}

What you have to do, is to create a component that uses the directive (it can be just for testing purpose):

您需要做的是创建一个使用该指令的组件(它可以仅用于测试目的):

@Component({
  selector: 'my-test-component',
  template: ''
})
class TestComponent {}

Now you need to create a module that has them declared:

现在您需要创建一个声明它们的模块:

describe('App', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestComponent,
        MyDirective
      ]
    });
  });

  // ...

});

You can add the template (that contains directive) to the component, but it can be handled dynamically by overwriting the template in test:

您可以将模板(包含指令)添加到组件中,但可以通过在测试中覆盖模板来动态处理:

it('should be able to test directive', async(() => {
  TestBed.overrideComponent(TestComponent, {
    set: {
      template: '<div my-directive></div>'
    }
  });

  // ...      

}));

Now you can try to compile the component, and query it using By.directive. At the very end, there is a possibility to get a directive instance using the injector:

现在您可以尝试编译该组件,并使用By.directive. 最后,有可能使用以下命令获取指令实例injector

TestBed.compileComponents().then(() => {
  const fixture = TestBed.createComponent(TestComponent);
  const directiveEl = fixture.debugElement.query(By.directive(MyDirective));
  expect(directiveEl).not.toBeNull();

  const directiveInstance = directiveEl.injector.get(MyDirective);
  expect(directiveInstance.directiveProperty).toBe('hi!');
}); 

# Old answer:

# 旧答案:

To test a directive you need to create a fake component with it:

要测试指令,您需要使用它创建一个假组件:

@Component({
  selector: 'test-cmp',
  directives: [MyAttrDirective],
  template: ''
})
class TestComponent {}

You can add the template in the component itself but it can be handled dynamically by overwriting the template in test:

您可以在组件本身中添加模板,但可以通过在测试中覆盖模板来动态处理:

it('Should setup with conversation', inject([TestComponentBuilder], (testComponentBuilder: TestComponentBuilder) => {
    return testComponentBuilder
      .overrideTemplate(TestComponent, `<div my-attr-directive></div>`)
      .createAsync(TestComponent)
      .then((fixture: ComponentFixture<TestComponent>) => {
        fixture.detectChanges();
        const directiveEl = fixture.debugElement.query(By.css('[my-attr-directive]'));
        expect(directiveEl.nativeElement).toBeDefined();
      });
  }));

Note that you're able to test what directive renders but I couldn't find the way to test a directive in a way components are (there is no TestComponentBuilder for directives).

请注意,您可以测试指令呈现的内容,但我找不到以组件方式测试指令的方法(没有用于指令的 TestComponentBuilder)。

回答by Jusef

Took me a while to find a good example, a good person on angular gitter channel pointed me to look at the Angular Material Design 2 repository for examples. You can find a Directive test example here. This is the test file for the tooltip directive of Material Design 2. It looks like you have to test it as part of a component.

我花了一段时间才找到一个很好的例子,角度 gitter 频道上的一个好人指点我查看 Angular Material Design 2 存储库中的示例。您可以在此处找到指令测试示例。这是 Material Design 2 的工具提示指令的测试文件。看起来您必须将其作为组件的一部分进行测试。