我正在测试React组件
import React from 'react';
import styled from 'styled-components';
const Input = styled.input``;
export default function FormInput (props) {
const { name, type, value, label, placeholder, onChange} = props;
return (
<Input
id={name}
name={name}
type={type}
placeholder={placeholder}
onChange={onChange}
value={value}
/>
)
};
使用此单元测试
test('it changes the value of the input', () => {
let currentValue = 'Initial value';
const setValue = (value) => {
currentValue = value;
}
const component = <FormInput
name={'firstName'}
placeholder={'Enter your first name'}
value={currentValue}
onChange={(e) => setValue(e.target.value)} />
render(component);
const input = screen.getByPlaceholderText('Enter your first name');
fireEvent.change(input, {target: {value: 'New value'}});
expect(currentValue).toBe('New value');
expect(input.value).toBe('New value');
});
关于输入值的断言为假,因为它仍然是初始值。此组件可在应用中正常运行。我在测试中设置错了什么?
我发现很容易模拟用户使用@testing-library/user-event
包输入的文本。
@testing-library/user-event
为什么不将setValue放在组件主体中?这个逻辑显然属于该组件,您应该具有:
import userEvent from '@testing-library/user-event';
test('it changes the value of the input', () => {
let currentValue = 'Initial value';
const setValue = (value) => {
currentValue = value;
}
const component = <FormInput
name={'firstName'}
placeholder={'Enter your first name'}
value={currentValue}
onChange={(e) => setValue(e.target.value)} />
render(component);
const input = screen.getByPlaceholderText('Enter your first name');
userEvent.type(input, 'New value');
expect(currentValue).toBe('New value');
expect(input.value).toBe('New value');
});
然后在您的测试中:
import React, { useState } from 'react';
import styled from 'styled-components';
const Input = styled.input``;
export default function FormInput (props) {
const { name, type, label, placeholder} = props;
const [value, setValue] = useState('');
return (
<input
id={name}
name={name}
type={type}
placeholder={placeholder}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
)
};
请注意,我使用import '@testing-library/jest-dom/extend-expect';
test('it changes the value of the input', () => {
const component = <FormInput
name={'firstName'}
placeholder={'Enter your first name'}
value={currentValue} />
render(component);
const input = screen.getByPlaceholderText('Enter your first name');
fireEvent.change(input, { target : { value : 'New value' } });
expect(input).toHaveValue('New value');
});
具有更多可读的匹配项。