我有一个包含 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'
我尝试添加
NgxPermissionsDirective
到TestBed
声明,但是该指令依赖于该库中的服务,我还必须注入(inject)它们。我还尝试导入 NgxPermissionsModule
本身,但它有它自己的错误。注入(inject)一大堆服务来测试一个简单的组件似乎违反直觉。有没有办法模拟这个指令?还是另一种解决方案?
最佳答案
我必须导入 NgxPermissionsModule
并提供NgxPermissionsService
;
TestBed.configureTestingModule({
imports: [
NgxPermissionsModule.forRoot(),
...
],
declarations: [
ProjectCardComponent,
...
],
providers: [
NgxPermissionsService,
...
]
})
关于angular - 如何测试包含第三方指令的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49378016/