Skip to main content

Unit Test - Testing React Component

To test React component, we're using React Testing Library because it encourages us to create accessible component and prevent testing implementation detail.

import React from 'react';
import { render } from '@testing-library/react';

function Component() {
return <div>{'Hello, world!'}</div>;
}

test('contains text hello world', () => {
const props = {};
const { getByText } = render(<Component {...props} />);
expect(getByText('Hello, world!')).toBeDefined();
});

Testing component with hook-based core API

If you use any hooks-based API from the framework, you need to use renderComponent function to make sure your component is rendered with correct context. It's similar to how you test page component.

import React from 'react';
import { useLocale } from '@traveloka/core';
import { renderComponent } from '@traveloka/core/test';

function Component() {
const locale = useLocale();
return <div>{locale.languageTag}</div>;
}

test('contains language tag', () => {
const props = {};
const { getByText } = renderComponent(<Component {...props} />);
expect(getByText('id-ID')).toBeDefined();
});

Custom _app wrapper

If you have custom _app that provide some kind of wrapper around your page component, you can either render your component inside that custom wrapper, or use App property

import React from 'react';
import { useLocale } from '@traveloka/core';
import { renderComponent } from '@traveloka/core/test';

import App from '../pages/_app';

function Component() {
const locale = useLocale();
return <div>{locale.languageTag}</div>;
}

test('contains text hello world', () => {
const props = {};
const { getByText } = renderComponent(<Component {...props} />, { App });
expect(getByText('id-ID')).toBeDefined();
});

Custom App Context

By default, renderComponent uses mocked data for global application data such as locale when rendering top level context. If you need to override those values, you can pass appContext option using 2nd argument

import React from 'react';
import { useLocale } from '@traveloka/core';
import { renderComponent } from '@traveloka/core/test';

import App from '../pages/_app';

function Component() {
const locale = useLocale();
return <div>{locale.languageTag}</div>;
}

test('render language tag', () => {
const props = {};
const appContext = {
languageTag: 'en-SG',
};
const { getByText } = renderComponent(<Component {...props} />, {
App,
appContext,
});
expect(getByText('en-SG')).toBeDefined();
});