Angular用testing-library+Jest测试子组件报输入属性错误如何解决?
问题根因&修复方案
1. 容器组件装饰器误用
你当前ShellUserComponent中定义的OutwellcomeMsg加了@Output()装饰器,属于使用错误:
@Output()是用来向父组件抛出自定义事件的装饰器,你此处的属性只是容器内部用来传递给子组件输入的普通公共属性,不需要加任何装饰器。- 这一错误会导致模板绑定时传值异常,也是引发你报错的原因之一。
修复后的容器组件代码:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-shell-user', templateUrl: './shell-user.component.html', styleUrls: ['./shell-user.component.scss'] }) export class ShellUserComponent implements OnInit { // 移除@Output()装饰器 OutwellcomeMsg: string | undefined; title = "Welcome to user!!" constructor() { } ngOnInit(): void { this.OutwellcomeMsg = this.title; } }
2. 测试模块未声明依赖组件
你看到的报错If 'app-user' is an Angular component and it has 'InwelcomeMsg' input, then verify that it is part of this module,核心是测试模块识别不了<app-user>标签:
- 如果你是在测试容器组件ShellUserComponent,需要在测试配置的
declarations数组中显式声明用到的UserComponent,否则Angular测试运行时不知道app-user是什么组件。 - 你当前贴的子组件单测本身配置没有问题,只要你的
UserComponent模板中显式渲染了InwelcomeMsg(比如加了{{ InwelcomeMsg }}插值语法),子组件单测可以正常运行。
容器组件测试用例参考:
import { render, screen } from '@testing-library/angular'; import { ShellUserComponent } from './shell-user.component'; import { UserComponent } from './user.component'; describe('ShellUserComponent', () => { it('should render welcome message correctly', async () => { await render(ShellUserComponent, { // 声明依赖的子组件 declarations: [UserComponent] }); expect(await screen.findByText(/Welcome to user!!/i)).toBeTruthy(); }); });
内容的提问来源于stack exchange,提问作者user2024080
相关产品推荐
相关产品推荐

