在Karma测试中解析带有连字符的变量在Angular模板中的方法如下:
将变量名中的连字符转换为驼峰命名法,例如将 my-variable
转换为 myVariable
。
在测试组件中声明一个与转换后的变量名相同的变量,并将其赋值为所需的值。例如:
component.myVariable = 'Value';
在测试中使用 fixture.detectChanges()
来触发变更检测。
使用 fixture.nativeElement
来获取渲染后的模板,并通过查询选择器选择包含变量的元素。例如:
const element = fixture.nativeElement.querySelector('.my-class');
expect(element.textContent).toContain('Value');
完整的示例代码如下:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should render variable with hyphen in template', () => {
component.myVariable = 'Value';
fixture.detectChanges();
const element = fixture.nativeElement.querySelector('.my-class');
expect(element.textContent).toContain('Value');
});
});
在上面的示例中,我们假设有一个带有 myVariable
变量的组件,并且模板中有一个类名为 my-class
的元素,我们想要测试该元素是否正确渲染了变量的值。