gpt4 book ai didi

javascript - 如何在 Angular 中使用 Jasmine 和 Karma 检查段落的 innerHTML 内容

转载 作者:太空狗 更新时间:2023-10-29 18:18:31 25 4
gpt4 key购买 nike

我有一个 Angular 组件,它有一个 <p>用一些文本标记。该段内的一个句子是粗体。我正在尝试在 Jasmine/Karma 中编写单元测试来检查 innerHTML内容。但是,我所有的尝试似乎都失败了。我会以错误的方式解决这个问题吗?这是我的标记和 JavaScript:

Angular 组件 HTML

<p>
Four score and seven years ago our fathers brought forth on this
continent, <b>a new nation</b>, conceived in Liberty, and dedicated to the
proposition that all men are created equal.
</p>

Jasmine 单元测试

describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let el: DebugElement;

beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
});

it('should display "a new nation" as bold text', () => {
const boldText = el.query(By.css('p')).nativeElement;
expect(boldText.innerHTML).toContain('<b>a new nation</b>');
});
});

此代码出现以下失败错误:

Expected 'Four score and seven years ago our fathers brought forth on this continent, <b _ngcontent-c1="">a new nation</b>, conceived in Liberty, and dedicated to the proposition that all men are created equal.'.

请注意 Angular 将自己的 ID 注入(inject)到 <b>标签。这是失败的原因吗?这甚至是进行此类测试的最佳方法吗?

谢谢!

最佳答案

直接查询粗体文本:

const boldText = el.query(By.css('p b')).nativeElement;
expect(boldText.textContent).toContain('a new nation');

关于javascript - 如何在 Angular 中使用 Jasmine 和 Karma 检查段落的 innerHTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51267023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com