Open WC测试简单LitElement组件失败,属性值未正确获取
问题:LitElement组件测试中属性值未正确绑定导致断言失败
组件代码(error.page.ts)
@customElement('sandbox-error') export class SandboxError extends LitElement { @property({type: Number}) errorCode = 500 @property({type: String}) errorText = "An error occurred" render() { return html` <div> <main> <div> <p>${this.errorCode}</p> <h1>${this.errorText}</h1> <slot></slot> </div> </main> </div> ` } } declare global { interface HTMLElementTagNameMap { 'sandbox-error': SandboxError } }
测试代码
import {SandboxError} from "../../src/components/error.page"; import {expect, fixture, html} from '@open-wc/testing'; describe("<sandbox-error>", () => { it('all attributes', async () => { const error:SandboxError = await fixture(html`<sandbox-error errorCode="404" errorText="foo">bar</sandbox-error>`); console.log(error.errorCode); expect(error.errorCode).to.equal(404); }); });
测试失败错误信息
test/components/error.page.test.ts:
❌
> all attributes
AssertionError: expected undefined to equal 404
at n.(test/components/error.page.test.ts:9:31)
问题原因
HTML属性是大小写不敏感的,LitElement会将TypeScript中驼峰命名的属性自动映射为短横线分隔的小写属性名。比如组件里的errorCode对应HTML属性error-code,errorText对应error-text。测试代码中使用了驼峰形式的errorCode="404",浏览器会将其解析为全小写的errorcode,无法和组件的errorCode属性匹配,导致属性值未正确赋值,最终断言失败。
解决方案
修改测试代码中的属性名,改用短横线分隔的形式:
import {SandboxError} from "../../src/components/error.page"; import {expect, fixture, html} from '@open-wc/testing'; describe("<sandbox-error>", () => { it('all attributes', async () => { // 将errorCode改为error-code,errorText改为error-text const error:SandboxError = await fixture(html`<sandbox-error error-code="404" error-text="foo">bar</sandbox-error>`); console.log(error.errorCode); expect(error.errorCode).to.equal(404); }); });
修改后,LitElement就能正确识别HTML属性并映射到组件的对应属性上,测试即可通过。
内容的提问来源于stack exchange,提问作者mathiasb
相关产品推荐
相关产品推荐

