Jest/Enzyme React branches



我正在尝试测试焦点函数,测试覆盖率告诉我有关分支的信息。 这是组件

import React, { Component } from 'react';
import Input from '../../components/common/input/Input';
import Button from '../../components/common/button/Button';
import isEmpty from '../../components/common/utils/isEmpty';
class Form extends Component {
state = { input: '', error: ''};
onChange = e => this.setState({ ...this.state, input: e.target.value });
onFocus = () => !isEmpty(this.state.error) && this.setState({ ...this.state, error: '' });
onSubmit = e => {
e.preventDefault();
if(isEmpty(this.state.input)) return this.setState({ ...this.state, error: 'error' });
};
render() {
const { input, error } = this.state;
return (
<form noValidate onSubmit={this.onSubmit} data-test='form'>
<Input
name='text'
label='City'
value={input}
onChange={this.onChange}
onFocus={this.onFocus}
error={error}
test='input'
/>
<Button text='Search' isLoading={false} type='submit' />
</form>
);
};
};
export default Form;

和测试文件

import React from "react";
import { mount } from 'enzyme';
import Form from "../../../layout/navbar/Form";
const setComponent = (props) => {
const component = mount(<Form {...props} />);
return component;
}
describe("Navbar `Form` component", () => {
let component;
beforeEach(() => {
component = setComponent();
});
it('Renders without errros', () => {
expect(component).toMatchSnapshot();
});
describe('`onFocus` func call to clear errors', () => {
it('Clears the error state if any', () => {
component.find(`button[type='submit']`).simulate('click');
component.find(`[data-test='input']`).simulate('focus');
expect(component.state().error).toEqual('');
});
});

}(;

测试通过,但是当我测试覆盖率时,我在第 11 行有一个分支,即onFocus函数

当我的状态没有错误时,如何测试另一个分支?

基本上是onfocus => if ERROR setState(...this.state, error: '' )

谢谢

来回答我自己的问题:

describe('`onFocus` event calls `onFocus` func', () => {
test('If `state.error` has No value', () => {
component.find('input').simulate('focus');
expect(isEmpty(component.state().error)).toBeTruthy();
expect(component.state().error).toEqual('');
});
test('If `state.error` has value', () => {
component.setState({ error: 'error' });
component.find('input').simulate('focus');
expect(isEmpty(component.state().error)).toBeTruthy();
expect(component.state().error).toEqual('');
});
});

最新更新