Reputation: 117
i want to check condition based on the boolean value
export const Button:React.FunctionComponent<ButtonProps>
const [loading, setLoading] = React.useState(false)
return(
<container
color={props.color},
border={5}
>
{loading ? <itemlist /> : props.title}
/>
)
I want to test if loading is true then render "<itemList/"> if not just show some title
I want to add some test cases for this
I tried this but i guess this seems to be wrong approach
test('check if loading is true', () => {
const isloadedProp = {
loading: false
}
const output = mount(<Button {...ButtonProps} />)
expect(output.find(container).find(itemlist)).toBeFalsy()
expect(output.find(container).title).toBe('ABC')
any suggestion or answers
Upvotes: 0
Views: 2160
Reputation: 2131
You can try jest.spyOn()
to gain control of React.useState
call.
const useStateSpy = jest.spyOn(React, 'useState');
const setLoadingMock = jest.fn();
let isLoadingState = true;
useStateSpy.mockImplementation(() => [isLoadingState, setLoadingMock]);
test('check if loading is true', () => {
isLoadingState = true;
// [loading, setLoading] = React.useState() will result in
// loading = true, setLoading = setLoadingMock
// your test code
});
test('check if loading is false', () => {
isLoadingState = false;
// [loading, setLoading] = React.useState() will result in
// loading = false, setLoading = setLoading Mock
// your test code
});
UPDATED: Rewrite to using just props and not state
As discussed, here is a solution to Button component using isLoading
prop instead of useState
.
Button.js
import React from 'react';
import Container from '....'; // insert path to Container component here
import ItemList from '....'; // insert path to ItemList component here
const Button = props => {
return (
<Container
color={props.color}
border={5}
>
{props.isLoading ? <Itemlist /> : props.title}
</Container>
);
};
export default Button;
Please mind that component names should always start with upper-case letter for React to distinguish between HTML tag and components.
Button.test.js
import React from 'react';
import { mount } from 'enzyme';
import Button from './Button';
const ButtonProps = {
color: 'red',
title: 'ABC',
};
describe('when isLoading === true', () => {
let output;
beforeAll(() => {
output = mount(<Button {...ButtonProps} isLoading />);
});
test('ItemList is rendered', () => {
expect(output.find('Itemlist')).toHaveLength(1);
});
test('title is not rendered', () => {
expect(output.find('Container').text()).not.toContain('ABC');
});
});
describe('when isLoading === false', () => {
let output;
beforeAll(() => {
output = mount(<Button {...ButtonProps} isLoading={false} />);
});
test('ItemList is not rendered', () => {
expect(output.find('Itemlist')).toHaveLength(0);
});
test('title is rendered', () => {
expect(output.find('Container').text()).toContain('ABC');
});
});
Upvotes: 1