angular - 如何测试包含第三方指令的组件

标签 angular angular-cli karma-jasmine

我有一个包含 ngxPermissionsOnly 的基本组件指令按预期工作。该库位于 github here .我使用@angular-cli 生成了组件,它也自动生成了单元测试。

例如零件

@Component({
    selector: 'project-card',
    template: '<div class="some-style"><div *ngxPermissionsOnly="['testPermission']"'>Hide Me</div></div>'
    styleUrls: ['./project-card.component.scss']
})
export class ProjectCardComponent implements OnInit {
    //Do some stuff here
}

例如测试
describe('ProjectCardComponent', () => {
    let component: ProjectCardComponent;
    let fixture: ComponentFixture<ProjectCardComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                ProjectCardComponent,
            ]
        })
        .compileComponents();
      }));

      beforeEach(() => {
          fixture = TestBed.createComponent(ProjectCardComponent);
          component = fixture.componentInstance;
          fixture.detectChanges();
      });

      it('should create', () => {
          expect(component).toBeTruthy();
      });
});

当我运行测试时,出现以下错误;
Can't bind to 'ngxPermissionsOnly' since it isn't a known property of 'div'

我尝试添加 NgxPermissionsDirectiveTestBed声明,但是该指令依赖于该库中的服务,我还必须注入(inject)它们。我还尝试导入 NgxPermissionsModule本身,但它有它自己的错误。注入(inject)一大堆服务来测试一个简单的组件似乎违反直觉。有没有办法模拟这个指令?还是另一种解决方案?

最佳答案

我必须导入 NgxPermissionsModule并提供NgxPermissionsService ;

TestBed.configureTestingModule({
  imports: [
    NgxPermissionsModule.forRoot(),
    ...
  ],
  declarations: [
    ProjectCardComponent,
    ...
  ],
  providers: [
    NgxPermissionsService,
    ...
  ]
})

关于angular - 如何测试包含第三方指令的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49378016/

相关文章:

javascript - 在 Angular 路由器的空路径上有条件地加载模块

android - IONIC 3 [ERROR] 运行 cordova run android 时发生错误(退出代码 1)

angular - ionic 2 返回 {"__zone_symbol__state":null ,"__zone_symbol__value" :"cyprus"}

import - Angular2 CLI Socket.io(第 3 方库导入)

Angular 2 npm js-sha1 导入

javascript - 使用 Karma-Jasmine 读取二进制文件

angular - 失败 : Unexpected directive 'ContactDetailsComponent' imported by the module 'DynamicTestModule' . 请添加@NgModule 注解

angular - 如何在模板驱动的表单中为 ngModelGroup 添加自定义验证

javascript - Angular-Cli 强制组件重新加载图像缓存

javascript - Jasmine : Timeout - Async callback was not invoked within timeout