Jest React Native how to test index.PLATFORM.js - reactjs

How can this be tested, to get jest coverage 100%
// #flow
import { AppRegistry } from 'react-native'
import App from './src/App'
AppRegistry.registerComponent('app', () => App)
The files that are this kind are 'index.ios.js' and 'index.android.js'

The default tests that come with a new React Native installation should do what you need as is.
import 'react-native';
import React from 'react';
import Index from './index.PLATFORM.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});

Related

Unit testing Chakra UI with Jest

Currently I am trying to unit test my application that is built with Create-React-App with typescript, and it is styled with chakraui. Chakrui includes a component ThemeProvider that must wrap the entire application as such.
This is my index.tsx file
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ThemeProvider, CSSReset } from "#chakra-ui/core/dist";
import { theme } from "#chakra-ui/core/dist";
ReactDOM.render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<CSSReset />
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
For every unit test that I write, I am having to wrap the component with ThemeProvider for the test to pass:
import React from "react";
import { render } from "#testing-library/react";
import { ThemeProvider } from "#chakra-ui/core/dist";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
render(
<ThemeProvider>
<App />
</ThemeProvider>
);
});
});
But this is very verbose, and must be done for every test that I write. Is there a way to do this just once in each .test.tsx file?
You could create your own theme wrapper function
import React from "react";
import { ThemeProvider } from "#chakra-ui/core/dist";
export const ThemeWrapper = ({ children }) => (
<ThemeProvider>{children}</ThemeProvider>
);
And then specify the wrapper in the test
import React from "react";
import { render } from "#testing-library/react";
import { ThemeWrapper } from "../testUtils";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
render(<App />, { wrapper: ThemeWrapper });
});
});
This marginally reduces the code for testing. You may be able to also go the route of creating a custom render function (following the steps for redux).
It could look something like
import React from "react";
import { render } from "#testing-library/react";
import { ThemeProvider } from "#chakra-ui/core/dist";
export const renderWithTheme = ui => {
const Wrapper = ({ children }) => (
<ThemeProvider>{children}</ThemeProvider>
);
return render(ui, { wrapper: Wrapper });
};
Basically the same as the wrapper above, but more integrated into a test render function. You can adjust the function signature a bit as well if you need to pass in a theme object, or other render options, this is just a simple example.
Now the test looks like
import React from "react";
import { renderWithTheme } from "../testUtils";
import App from "./App";
describe("<App />", () => {
test("smoke test", () => {
renderWithTheme(<App />);
});
It might be the case that Jest might be mocking your imports from #chakra-ui/core/dist (depending on your jest configuration) which might be resulting your imported chakra-ui components to be undefined.
Importing the Theme Provider and wrapping it everytime with your renders might be one way to do it. The problem might arise when you have multiple components in your index.tsx. So, you might not want to import each and every component.
In that case, you will want to import the actual components from #chakra-ui/core.
The best way (according to me) to do so in Jest is:
jest.mock("#chakra-ui/core", () => {
const ui = jest.requireActual("#chakra-ui/core");
return {
...ui,
customKey: 'customValue',
};
})
This way you can even add custom function and key-values to the imported module.

How to set intellisense for react testing library using typescript

I just downloaded Create-React-App which uses react testing library. I do not get intellisense when I use it's methods (Example : toBeInTheDocument) . How to set intellisense ? Do we have any type definitions for RTL?
import React from 'react';
import { render } from '#testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
You need to import '#testing-library/jest-dom'

Jest - unexpected identifier - Component testing w Jest react-native

I keep getting this error when trying to test a button component. I have changed Jest's config settings here and there but nothing has worked, can anyone tell me the answer so I can stop pulling my hair out?
I am using expo to demo the app, the problem seems to lie within the font that it's trying to render on the nav button, Jest/React doesn't understand it.
The failure:
FAIL tests/Components/NavigationButton.test.js
● Test suite failed to run
C:\..\node_modules\#expo\vector-icons\Zocial.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Zocial from './build/Zocial';
^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (node_modules/react-native-elements/src/helpers/getIconType.js:1:1)
NavigationButton.js:
import React from "react";
import { StyleSheet } from "react-native";
import { Button } from "react-native-elements";
import Icon from "react-native-vector-icons/FontAwesome";
import { withNavigation } from 'react-navigation';
const NavigationButton =(props) => {
return (
<Button data-test="nav_button"
icon={<Icon name={props.icon} size={30} color="white" style={styles.iconStyle} />}
raised
color="white"
buttonStyle={styles.button}
title={props.title}onPress={() => props.navigation.navigate(props.navName)}
/>
);
};
const styles = StyleSheet.create({
button: {
minWidth:150,
alignSelf:'center',
},
iconStyle:{
marginHorizontal:10
}
});
export default withNavigation(NavigationButton);
NavigationButton.test.js:
/**
* #format
*/
import 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAtt } from '../../Utils/test_utils';
import NavigationButton from '../../src/Components/NavigationButton'
// Note: this is just for use with Jest snapshot testing
// and comes packaged with react-native init project.
// You do not need this if using Enzyme 'toMatchSnapshot' etc.
import renderer from 'react-test-renderer';
// setup for shallow rendering component, saves having to do it in every test in this file
const setup = (props = {}) => {
const component = shallow(<NavigationButton {...props} />);
return component;
};
describe('NavigationButton tests: ', () => {
let component;
beforeEach(() => {
component = setup();
});
it('Button renders correctly: ', () => {
console.log(component.debug());
const wrapper = findByTestAtt(component, 'nav_button');
expect(wrapper.length).toBe(1);
});
});
Using the jest-expo preset solved the problem for me. The documentation explains it well: https://www.npmjs.com/package/jest-expo. The issue seemed to be that the import keyword wasn't being transformed, I'm not clear on why but it came up in an issue here: https://github.com/expo/expo/issues/5296

How do I Import a manually mocked module with mocked data using jest and enzyme?

My test doesn't seem to importing my manual mock under __mocks__/Auth.js.
I have a module that I use, Auth.js in my react application, App.js. I am trying to mock that module using a manual mock by making a mocked file under __mocks__/Auth.js. My __mocks__ is at the same file level as App.js and Auth.js.
I have a repo here: https://github.com/chaselw/reactTesting
Or my test is below:
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16'
import App from './App';
Enzyme.configure({ adapter: new EnzymeAdapter() });
test('logged in false', () => {
jest.mock('./Auth.js'); //Trying to get `auth.isLoggedIn() === false`
const wrapper = mount(<App />);
console.log(wrapper.debug())
expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
})
Expected result is that the test would return a "Logged-In-False" div from Login module after the if check on auth.isLoggedIn(). However I get the "true" div back.
In the test if I do: console.log(wrapper.auth.isLoggedIn()), it returns .isLoggedIn() is undefined.
I am new to React, jest and enzyme. I have no idea what is wrong, any help would be great! Thanks.
The solution was simple. jest.mock('./Auth.js') needs to be not inside a test, but rather at the top level as the imports.
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16'
import App from './App';
jest.mock('./Auth');
Enzyme.configure({ adapter: new EnzymeAdapter() });
test('logged in false', () => {
//Trying to get `auth.isLoggedIn() === false`
const wrapper = mount(<App />);
console.log(wrapper.debug())
expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
})

jest with enzyme testing shallow stucks

I am trying to test a component in react native, but it gets stuck on the shallow test. If I pass an incorrect component, the test fails, but if I pass a react-native text component it gets stuck.
import React from "react";
import Enzyme, {shallow, mount} from "enzyme";
import Screen from 'react-native-login'
import Adapter from "enzyme-adapter-react-16"
import { configure } from 'enzyme'
import {Text} from 'react-native'
configure({ adapter: new Adapter() })
test('render with react-native component', () => {
const wrapper = shallow(<Text />); // Hangs
})

Resources