我有一个组件,其中包含一些*ngIf语句,其中大多数语句类似于以下
<ul *ngFor="let item of items">
<li>
<ng-container *ngIf="itemCount && item.GroupId == 4">
<span class="bridge">{{itemCount}}</span>
</ng-container>
</li>
... and so on
在我的规范文件中,我有一个测试,它试图检查itemCount不为null/空并且groupId=4的情况…然后检查span是否包含正确的项计数。
我花了几个小时研究这种变体,但无论我尝试什么,访问跨度的尝试都会导致null,测试失败。
这里有一个测试的例子
if('should show the correct item count', () =>{
let component = fixture.componentInstance;
component.itemCount = 4;
fixture.detectChanges();
let bridge = fixture.debugElement.query(By.css('.bridge'));
expect(bridge).tobeTruthy();
});
正如我在上面所说的,通过多次尝试,无论发生什么,这总是无效的。我已经调试了测试,并确认使用了正确的groupId。我还确认了itemCount不是null或空的,所以*ngIf的两个条件都应该满足——但跨度不存在,所以我不得不推测出了问题。
请原谅拼写错误,我正在手动复制代码,但它目前正在运行,只是没有成功。
有指针吗?
更新:
以下是更多信息,beforeEach,其中组件填充有伪数据。
const ItemServiceStub = jasmine.createSpyObj('ItemService', ['getItems']);
beforeEach(() =>{
TestBed.configureTestingModule({
declarations: [ItemComponent],
providers: [{provide: ItemService, useValue: ItemServiceStub}]
}).compileComponents();
});
beforeEach(() => {
itemService = Testbed.inject(ItemService);
spyOn(itemService, 'getItems').and.callFake(() => of(fakeItems));
fixture = TestBed.createComponent(ItemComponent);
fixture.autoDetectChanges();
});
更新2这是设置的假数据
describe('item tests', () => {
let fakeItems: Item[];
fakeItems = [
{GroupId: '2', ItemName: 'test', isExternal: false},
{GroupId: '3', ItemName: 'testing', isExternal: false},
{GroupId: '4', ItemName: 'test item', isExternal: false}
];
});
试试这个:
it('should show the correct item count', () =>{
let component = fixture.componentInstance;
component.items = [...fakeItems];
component.itemCount = 4;
fixture.detectChanges();
let bridge = fixture.debugElement.query(By.css('.bridge'));
console.log(bridge); // make sure it logs something to the console
expect(bridge).toBeTruthy();
});
如果这不起作用,我认为在ul
的顶部有一个*ngIf
,它不是真的,因此这个ul
不会被显示。
要对此进行测试,请尝试:
<ul class="dummy-class" *ngFor="let item of items">
<li>
<ng-container *ngIf="itemCount && item.GroupId == 4">
<span class="bridge">{{itemCount}}</span>
</ng-container>
</li>
it('should show the correct item count', () =>{
let component = fixture.componentInstance;
component.items = [...fakeItems];
component.itemCount = 4;
fixture.detectChanges();
let bridge = fixture.debugElement.query(By.css('ul.dummy-class'));
console.log(ul); // make sure it logs something to the console
expect(ul).toBeTruthy();
});