I have a custom hook that returns true or false by checking if the view is a mobile or a desktop view.
I'm trying to write a test for a page that uses this hook. I tried as following
import { useIsMobile } from '../../../../hooks/useIsMobile';
jest.mock('../../../../hooks/useIsMobile');
describe('Form', () => {
beforeEach(jest.resetAllMocks);
it('should render the correct header style for deliver to label in desktop view', () => {
(useIsMobile as jest.Mock).mockReturnValueOnce(false);
const delivery_label = screen.getByTestId('label1');
expect(delivery_label.tagName).toEqual('H3');
});
it('should render the correct header style for deliver to label in mobile view', () => {
(useIsMobile as jest.Mock).mockReturnValueOnce(true);
const delivery_label = screen.getByTestId('label1');
expect(delivery_label.tagName).toEqual('H4');
});
}
But I'm getting this error
TypeError: _useIsMobile.useIsMobile.mockReturnValueOnce is not a function
What does this mean and how can i fix this?
Related
I'm trying to get unit test coverage for the code in red (see screenshot) using react-testing-library. Would anyone know what unit test would cover this? I'm still learning the react-testing-library. TIA
screenshot of code here showing red, uncovered code
If you don't open the screenshot above, the code inside this function is what needs to be covered.
const togglePopover = () => {
setToolTipOpen((prev) => !prev);
};
actual full component code block:
import React, { FunctionComponent, useState, KeyboardEvent, useRef, useEffect } from 'react';
import styles from './InfoPopover.module.scss';
import { Popover, PopoverBody } from 'x'
import { PopperPlacementType } from '#material-ui/core';
import { ReactComponent as InfoIcon } from '../../../assets/icons/tooltipIcon.svg';
export interface PopperProps {
placement?: PopperPlacementType;
tipMessage: React.ReactNode | string;
stringedTipMessage: string;
}
const InfoPopover: FunctionComponent<PopperProps> = ({
placement,
tipMessage,
stringedTipMessage
}: PopperProps) => {
const [toolTipOpen, setToolTipOpen] = useState(false);
const togglePopover = () => {
setToolTipOpen((prev) => !prev);
};
const handleBlur = () => {
setToolTipOpen(false);
};
return (
<>
<button
id="popoverTarget"
className={styles.tooltipButton}
onBlur={handleBlur}
aria-label={`Tooltip Content - ${stringedTipMessage}`}
>
<InfoIcon aria-label="status tooltip" />
</button>
<Popover
target="popoverTarget"
trigger="legacy"
toggle={togglePopover}
placement={placement}
isOpen={toolTipOpen}
arrowClassName={styles.toolTipArrow}
popperClassName={styles.toolTipPopout}
>
<PopoverBody>{tipMessage}</PopoverBody>
</Popover>
</>
);
};
export default InfoPopover;
With React Testing Library, the approach is to test what the user can see/do rather than test the internals of your application.
With your example, assuming you are trying to test a simple open/close popup user flow then the user would be seeing a button, and when they activate that button they would see a popover. A simple RTL approach would be as follows:
const popoverTipMessage = "My popover message";
render(<InfoPopover tipMessage={popoverTipMessage} />);
// Popover isn't activated, so it shouldn't be in the DOM
expect(screen.getByText(popoverTipMessage)).not.toBeInDocument();
// Find button and click it to show the Popover
fireEvent.click(screen.getByRole('button', {
name: /tooltip content/i
}));
// Popover should now be activated, so check if it's visible (in the DOM)
await waitFor(() => {
// This relies on RTL's text matching to find the component.
expect(screen.getByText(popoverTipMessage)).toBeInDocument();
});
// Find button and click it again to hide the Popover
fireEvent.click(screen.getByRole('button', {
name: /tooltip content/i
}));
// Popover should now be hidden, so check if the DOM element has gone
// Note: There are other ways of checking appearance/disappearance. Check the RTL docs.
await waitFor(() => {
// This relies on RTL's text matching to find the component but there are other better ways to find an element
expect(screen.getByText(popoverTipMessage)).not.toBeInDocument();
});
The query methods I've used above are some of the basic ones, however RTL has many different queries to find the element you need to target. It has accessibility at the forefront of its design so leans heavily on these. Take a look in the docs: https://testing-library.com/docs/react-testing-library/example-intro
Have a React Ionic app where I need to determine if the app is running on an iOS device. I've done that by importing isPlatform.
import { isPlatform } from "#ionic/core";
const isIOS = isPlatform("ios");
I've tried the following and when isPlatform is called it still returns false.
jest.mock("#ionic/core", () => ({
isPlatform: () => {
return true;
}
}));
How do I mock isPlatform in my unit test using jest so it returns true?
Figured it out. I needed to mock ionic/core in order for it to work.
jest.mock("#ionic/core");
import * as Ionic from '#ionic/core';
(Ionic as any).isPlatform = jest.fn(() => true);
If component only uses isFlatform in #ionic/core you can mock one function isFlatform:
jest.mock("#ionic/core", () => ({
isPlatform: () => true,
}));
but when component use another function and you only want to mock isFlatform you can use:
jest.mock("#ionic/core", () => ({
...jest.requireActual("#ionic/core"),
isPlatform: () => true,
}));
Similar to the previous responses but using a slightly more flexible approach to be able to mock the result based on what we want to test in each scenario. In our app we're using Angular but this approach should be working as well for React.
The idea is to define a mockIsPlatform() function:
// Note: on our app, we're importing the `isPlatform` helper method
// from `#ionic/angular` but that's not really important.
let mockIsPlatform: (key: string) => boolean;
jest.mock('#ionic/angular', () => ({
...(jest.requireActual('#ionic/angular') as object),
isPlatform: (key: string) => mockIsPlatform(key),
}));
Our service has some methods that use the isPlatform() method behind the scenes:
public isIos(): boolean {
return isPlatform('ios');
}
public isAndroid(): boolean {
return isPlatform('android');
}
So we can now test those methods like this:
test('detect platform', () => {
// Simulate ios platform
mockIsPlatform = (key) => key === 'ios';
expect(myServiceInstance.isIos()).toBeTruthy();
expect(myServiceInstance.isAndroid()).toBeFalsy();
// Simulate android platform
mockIsPlatform = (key) => key === 'android';
expect(myServiceInstance.isIos()).toBeFalsy();
expect(myServiceInstance.isAndroid()).toBeTruthy();
})
Code structure is as same as given below:
FunctionComponent.js
...
const [open, handler] = useState(false);
setTimeout(() => {handler(true);}, 2000);
...
return (
...
<div className={active ? 'open' : 'close'}>
)
comp.test.js
jest.useFakeTimers();
test('test case 1', () => {
expect(wrapper.find('open').length).toBe(0);
jest.advanceTimersByTime(2000);
expect(wrapper.find('open').length).toBe(1);
jest.useRealTimers();
});
The problem is that the expression written in bold in test is saying the length of open class is still 0, so actual and expected are not meeting.
You want to test the outcome of the hook and not the hook itself since that would be like testing React. You effectively want a test where you check for if the open class exists and then doesn't exist (or vice versa), which it looks like you're trying.
In short, to solve your issue you need to use ".open" when selecting the class. I would also suggest using the .exists() check on the class instead of ".length()" and then you can use ".toBeTruthy()" as well.
You could look into improve writing your tests in a Jest/Enzyme combined format as well:
import { shallow } from 'enzyme';
import { FunctionComponent } from './FunctionComponent.jsx';
jest.useFakeTimers();
describe('<FunctionCompnent />', () => {
const mockProps = { prop1: mockProp1, prop2: mockProp2, funcProp3: jest.fn() };
const wrapper = shallow(<FunctionComponent {...mockProps} />);
afterEach(() => {
jest.advanceTimersByTime(2000);
});
afterAll(() => {
jest.useRealTimers();
});
it('should render as closed initially', () => {
expect(wrapper.find('.close').exists()).toBeTruthy();
// you could also add the check for falsy of open if you wanted
// expect(wrapper.find('.open').exists()).toBeFalsy();
});
it('should change to open after 2 seconds (or more)', () => {
expect(wrapper.find('.open').exists()).toBeTruthy();
// you could also add the check for falsy of close if you wanted
// expect(wrapper.find('.close').exists()).toBeFalsy();
});
});
EDIT: Sorry realised I wrote the test backwards after checking your code again, they should be fixed now.
I have a React component which renders a list of components. I'm running some tests which mock the axios module which loads in the users from JSONPlaceHolder. All works fine including the the async test and it's mocks data as expected. However if you look at the code below it only passes as long as the first test is commented out? Am I missing something? Been banging my head for ages. Is there some cleanup that needs to be done between tests? Thanks in advance.
import { waitForElement } from 'enzyme-async-helpers';
import UsersList from '../UsersList';
import axios from 'axios';
const mockUsers = [
{
"id": 1,
"name": "Leanne Mock",
"username": "Bret",
"email": "Sincere#april.biz"
},
{
"id": 2,
"name": "John Mock",
"username": "Jospeh",
"email": "wacky#april.biz"
}
]
axios.get.mockImplementationOnce(() => Promise.resolve({
data: mockUsers
}))
describe('<UsersList /> tests:', () => {
//WHEN I UNCOMMENT THIS TEST THE SECOND TEST FAILS?
test('It renders without crashing', (done) => {
// const wrapper = shallow(<UsersList />);
});
test('It renders out <User /> components after axios fetches users', async () => {
const wrapper = shallow(<UsersList />);
expect(wrapper.find('#loading').length).toBe(1); //loading div should be present
await waitForElement(wrapper, 'User'); //When we have a User component found we know data has loaded
expect(wrapper.find('#loading').length).toBe(0); //loading div should no longer be rendered
expect(axios.get).toHaveBeenCalledTimes(1);
expect(wrapper.state('users')).toEqual(mockUsers); //check the state is now equal to the mockUsers
expect(wrapper.find('User').get(0).props.name).toBe(mockUsers[0].name); //check correct data is being sent down to User components
expect(wrapper.find('User').get(1).props.name).toBe(mockUsers[1].name);
})
})
The Error message I get is:
The render tree at the time of timeout:
<div
id="loading"
>
Loading users
</div>
console.warn node_modules/enzyme-async-helpers/lib/wait.js:42
As JSON:
{ node:
{ nodeType: 'host',
type: 'div',
props: { id: 'loading', children: ' Loading users ' },
key: undefined,
ref: null,
instance: null,
rendered: ' Loading users ' },
type: 'div',
props: { id: 'loading' },
children: [ ' Loading users ' ],
'$$typeof': Symbol(react.test.json) }
Test Suites: 1 failed, 1 total
Tests: 2 failed, 2 total
You only mock the first axios.get call because you are using mockImplementationOnce.
When you shallow(<UsersList />) twice, the second time is timing out loading the users.
You can add a beforeEach method with a mockResolvedValueOnce inside, to mock the axios.get before every single test:
beforeEach(() => {
axios.get.mockResolvedValueOnce({data: mockUsers});
}
Having the same issue, but I'm not making a request. I'm building a client-side React application and testing for the render of sub-components. I have an image carousel that loads on my Home component and I'm writing tests for it. If I comment out all but one test (any test) it passes. If I have more than one test (any combination of tests), it fails. I've tried async/await/waitFor, react-test-renderer, using done() - nothing seems to change this behavior.
import { render, screen } from '#testing-library/react';
import ImageCarousel from '../carousel/ImageCarousel';
import localPhotos from '../../data/localPhotos';
// passing in the full array of images is not necessary, it will cause the test to time out
const testArray = localPhotos.slice(0, 3);
describe('Image Carousel', () => {
it('renders without error', () => {
render(<ImageCarousel images={testArray} />);
const imageCarousel = screen.getByTestId('image-carousel');
expect(imageCarousel).toBeInTheDocument();
});
// it('displays the proper alt text for images', () => {
// render(<ImageCarousel images={testArray} />);
// const photo1 = screen.getByAltText(localPhotos[0].alt);
// const photo2 = screen.getByAltText(localPhotos[1].alt);
// expect(photo1.alt).toBe(localPhotos[0].alt);
// expect(photo2.alt).toBe(localPhotos[1].alt);
// });
// it("displays full-screen icons", () => {
// render(<ImageCarousel images={testArray} />);
// const fullScreenIcons = screen.getAllByTestId('full-screen-icon');
// expect(fullScreenIcons.length).toBe(testArray.length);
// })
// shows controls when showControls is true
// does not show controls when showControls is false
// it('displays the proper number of images', () => {
// render(<ImageCarousel images={testArray} />);
// const carousel_images = screen.getAllByTestId('carousel_image');
// expect(carousel_images.length).toBe(testArray.length);
// });
// calls next when clicked
// calls previous when clicked
// returns to first image when next is clicked and last image is shown
// moves to last image when previous is clicked and first image is shown
});
I have a mock module like this in my component test file
jest.mock('../../../magic/index', () => ({
navigationEnabled: () => true,
guidanceEnabled: () => true
}));
these functions will be called in render function of my component to hide and show some specific feature.
I want to take a snapshot on different combinations of the return value of those mock functions.
for suppose I have a test case like this
it('RowListItem should not render navigation and guidance options', () => {
const wrapper = shallow(
<RowListItem type="regularList" {...props} />
);
expect(enzymeToJson(wrapper)).toMatchSnapshot();
});
to run this test case I want to change the mock module functions return values to false like this dynamically
jest.mock('../../../magic/index', () => ({
navigationEnabled: () => false,
guidanceEnabled: () => false
}));
because i am importing RowListItem component already once so my mock module wont re import again. so it wont change. how can i solve this ?
You can mock the module so it returns spies and import it into your test:
import {navigationEnabled, guidanceEnabled} from '../../../magic/index'
jest.mock('../../../magic/index', () => ({
navigationEnabled: jest.fn(),
guidanceEnabled: jest.fn()
}));
Then later on you can change the actual implementation using mockImplementation
navigationEnabled.mockImplementation(()=> true)
//or
navigationEnabled.mockReturnValueOnce(true);
and in the next test
navigationEnabled.mockImplementation(()=> false)
//or
navigationEnabled.mockReturnValueOnce(false);
what you want to do is
import { navigationEnabled, guidanceEnabled } from '../../../magic/index';
jest.mock('../../../magic/index', () => ({
navigationEnabled: jest.fn(),
guidanceEnabled: jest.fn()
}));
describe('test suite', () => {
it('every test', () => {
navigationEnabled.mockReturnValueOnce(value);
guidanceEnabled.mockReturnValueOnce(value);
});
});
you can look more about these functions here =>https://facebook.github.io/jest/docs/mock-functions.html#mock-return-values
I had a hard time getting the accepted answers to work - my equivalents of navigationEnabled and guidanceEnabled were undefined when I tried to call mockReturnValueOnce on them.
Here's what I had to do:
In ../../../magic/__mocks__/index.js:
export const navigationEnabled = jest.fn();
export const guidanceEnabled = jest.fn();
in my index.test.js file:
jest.mock('../../../magic/index');
import { navigationEnabled, guidanceEnabled } from '../../../magic/index';
import { functionThatReturnsValueOfNavigationEnabled } from 'moduleToTest';
it('is able to mock', () => {
navigationEnabled.mockReturnValueOnce(true);
guidanceEnabled.mockReturnValueOnce(true);
expect(functionThatReturnsValueOfNavigationEnabled()).toBe(true);
});