我有一个包含df1 <- structure(list(Col1 = c("A=5", "A=6", "B=2"), Col2 = c("C=1",
"B=3", "C=3"), Col3 = c("E=5", "D=6", "D=3"), Col4 = c("F=4",
"E=4", "E=3"), Col5 = c("G=2", "F=4", "F=7")), .Names = c("Col1",
"Col2", "Col3", "Col4", "Col5"), class = "data.frame", row.names = c(NA,
-3L))
指令的基本组件,该指令正在按预期工作。该库位于github here上。我使用@ angular-cli生成了组件,它也自动生成了单元测试。
e.g。成分
ngxPermissionsOnly
e.g。测试
@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
本身,但它有自己的错误。注入一大堆服务来测试一个简单的组件似乎是违反直觉的。有没有办法模仿这个指令?还是另一种解决方案?
答案 0 :(得分:2)
我必须导入NgxPermissionsModule
并提供NgxPermissionsService
;
TestBed.configureTestingModule({
imports: [
NgxPermissionsModule.forRoot(),
...
],
declarations: [
ProjectCardComponent,
...
],
providers: [
NgxPermissionsService,
...
]
})
答案 1 :(得分:1)
我认为您可以在测试文件中使用相同的名称创建mocked / stub指令,并在测试中声明它。
或者您可以使用CUSTOM_ELEMENTS_SCHEMA或NO_ERRORS_SCHEMA(更多信息here)作为测试中的架构:
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
describe('ProjectCardComponent', () => {
let component: ProjectCardComponent;
let fixture: ComponentFixture<ProjectCardComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ProjectCardComponent,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProjectCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
这将跳过DOM中的未知属性,但如果您想要实际测试该指令如何与您的组件一起使用,则不应使用此属性。