我想测试 api 调用和返回的数据,这些数据应该显示在我的功能组件中。我创建了执行 api 调用的 List 组件。我希望返回的数据显示在组件中,为此我使用了 useState 钩子。组件如下所示:
const List: FC<{}> = () => {
const [data, setData] = useState<number>();
const getData = (): Promise<any> => {
return fetch('https://jsonplaceholder.typicode.com/todos/1');
};
React.useEffect(() => {
const func = async () => {
const data = await getData();
const value = await data.json();
setData(value.title);
}
func();
}, [])
return (
<div>
<div id="test">{data}</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我写了一个测试,其中我嘲笑了 fetch 方法。我检查 fetch 方法是否已被调用并且它确实发生了。不幸的是,我不知道如何测试响应返回的值。当我尝试 console.log 时,我只是得到 null,我想得到“示例文本”。我的猜测是我必须等待从 Promise 返回的这个值。不幸的是,尽管尝试使用行为和等待方法,但我不知道如何实现它。这是我的测试:
it('test', async () => {
let …Run Code Online (Sandbox Code Playgroud) unit-testing typescript reactjs react-testing-library react-hooks
我正在创建带有验证的 Angular 6 表单。我只想在提交表单后显示错误消息。重要的事实是,在打字过程中消息不应该改变。因此,例如当用户没有在输入中输入任何内容然后提交表单时,应该会出现所需的消息。之后,当用户输入内容时,消息应该一直可见,直到下一次提交按钮按下。此外,当满足先前的规则时,错误消息不应更改为另一个。老实说,我不知道是否可以使用 Reactive Forms。
应用程序组件.html
<form [formGroup]="form" novalidate (ngSubmit)="submit()" #myform="ngForm">
<input class="input" type="text" formControlName="firstName" />
<p *ngIf="form.get('firstName').hasError('required') && myform.submitted">
Name is required
</p>
<p *ngIf="form.get('firstName').hasError('minlength') && myform.submitted">
Min length of string is {{form.controls.firstName.errors.minlength.requiredLength}}
</p>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
export class AppComponent {
form: FormGroup
constructor(private fb: FormBuilder,) {
this.form = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(5)]]
});
}
submit() {
console.log(this.form);
}
}
Run Code Online (Sandbox Code Playgroud)
演示:堆栈闪电战
谢谢你的帮助!
我想使用 Formik 和 Yup 创建动态表单。按下加号按钮时,应添加新的输入。但是,当我创建验证架构时,onSubmit 方法没有调用。当我删除validationSchema时,我可以在控制台中看到日志。
这是我的代码:
interface Props {
data?: string;
onSubmit?: Function
}
interface IFormValues {
people: {name: string, surname: string}[]
}
const FieldComponent = ({field, form: { touched, errors }}) => {
const error = getIn(errors, field.name);
const touch = getIn(touched, field.name);
return (
<div>
<input type="text" name={field.name} onChange={field.onChange}/>
{touch && error ? <p>{error}</p> : null}
</div>
)
}
const FieldArrayComponent = (arrayHelpers) => (
<div>
{arrayHelpers.form.values.people.map((person, index) => (
<div key={index}>
<Field name={`people.${index}.name`} component={FieldComponent}/>
<Field name={`people.${index}.surname`} …Run Code Online (Sandbox Code Playgroud) forms ×2
javascript ×2
reactjs ×2
angular ×1
formik ×1
react-hooks ×1
typescript ×1
unit-testing ×1