Jest encountered an unexpected token with SwiperJs - reactjs

I am creating some snapshot testing with jest. It gives me error with SwiperJs.
In my test i just want to have snapshot that renders component. I also have a single feature component which renders a feature comes from static data. Its test is passing without problem.
When i run test it gives me that eror.
SyntaxError: Unexpected token 'export'
> 2 | import { Swiper, SwiperSlide } from 'swiper/react';
Features.jsx
import { Link } from 'react-router-dom';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Pagination } from 'swiper';
import featuresData from '../../data/featuresData';
import Feature from './Feature';
import illustration from '../../assets/features-illustration.svg';
import star from '../../assets/star.svg';
const Features = () => {
return (
////rest of the component
<Swiper
pagination={{
clickable: true,
}}
modules={[Pagination]}
>
///rest of the swiper
)
}
Features.test.jsx:
import renderer from 'react-test-renderer';
import Features from '../Features';
describe('Features', () => {
it('renders correctly', () => {
const tree = renderer.create(<Features />).toJSON();
expect(tree).toMatchSnapshot();
});
});
I installed jest packages with :
yarn add --dev jest babel-jest #babel/preset-env #babel/preset-react react-test-renderer

The solution for me was to introduce the following into my jest configuration file:
module.exports = {
// ...
transformIgnorePatterns: ['node_modules/(?!(swiper|ssr-window))']
}
Depending on your setup this may differ. In my case I'm extending a config provided by a framework, so all we needed was the above, however see here for a more detailed configuration.

Related

Testing a Typescript React Component Giving Error on getByText

I'm trying to add unit testing to an application written with Typescript and React. I have a very basic component just for the sake of simplicity.
import React from "react";
import ReactDOM from "react-dom";
type TypeProps = { }
type TypeState = { }
class App extends React.Component<TypeProps, TypeState> {
constructor(props:TypeProps) {
super(props);
this.state = { };
}
render() {
return(<p>Literally Nothing</p>);
}
}
function renderApp() {
let AppElement = document.getElementById("app");
if(AppElement) { ReactDOM.render(<App />, AppElement); }
}
renderApp();
export { renderApp }
Then installed what I believed to be everything required for the tests
npm install --save-dev jest ts-jest #types/jest
npm install --save-dev #testing-library/jest-dom #testing-library/react
With jest.config.json as
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom'
};
So this is all fine and I have a unit test of nothing
import React from "react";
import ReactDOM from "react-dom";
import "#testing-library/jest-dom";
import { render } from "#testing-library/react";
import { renderApp } from "./App";
test("Literally Nothing", function() {
renderApp();
expect(getByText("App")).toBeInTheDocument();
});
But it is throwing the following error on build and npm run test
TS2304: Cannot find name 'getByText'.
Am I missing an install or configuration step?
You are missing getByText which is not imported anywhere.
I'd suggest you import screen
import { screen } from '#testing-library/react';
//....
renderApp();
const appText = screen.getByText("App");
expect(appText).toBeInTheDocument();
Also this will always assets false, because on your component there isn't any text with the value "App", the onlye text that will render is "Literally Nothing".
So like this will work:
const appText = screen.getByText("Literally Nothing");
expect(appText).toBeInTheDocument();

Jest-dom give the error "TypeError: expect(...).toHaveStyle is not a function"

I'm trying to use jest-dom to test a component's styles, and I'm having the error:
"TypeError: expect(...).toHaveStyle is not a function"
My component is a simple link with styled-components:
import styled from 'styled-components'
export const Link = styled.a`
color: #fff;
`
In my test I'm doing:
describe('Link', () => {
it('should display color on the link', () => {
render(<Link href="/x">Test</Link>)
}
expect(screen.getByRole('link', { name: /test/i })).toHaveStyle({ color: '#fff' })
}
I created a settings file (jest.config.js) with:
module.exports = {
setupFilesAfterEnv: ['<rootDir>/.jest/setup.js'],
}
At the root of the project I created the .jest / setup.js file and imported the js-dom:
import '#testing-library/jest-dom'
From https://testing-library.com/docs/svelte-testing-library/setup/
6.2 Add the following to your Jest configuration in package.json
{
"setupFilesAfterEnv": ["#testing-library/jest-dom/extend-expect"]
}
You could add it to your jest.config.js since you already have that, rather than package.json.
Since #testing-library/dom v5.0.0, there are some breaking changes compare/v4.2.4...v5.0.0
Before v5.0.0, you should use import '#testing-library/jest-dom/extend-expect';
Since v5.0.0, you should use import '#testing-library/jest-dom';
You didn't add the matchers for expect correctly. That's the reason you get the error.
you can try this :
import { toHaveStyle } from '#testing-library/jest-dom'
expect.extend({ toHaveStyle })
it works for me.
Use the following versions in your package:
"dependencies": {
"#types/styled-components": "5.9.1",
"styled-components": "^5.2.0"
},
and import this package into your test file:
import '#testing-library/jest-dom/extend-expect'
I found the answer from this link
To be short:
Run: npm install --save-dev #testing-library/jest-native
Add: import '#testing-library/jest-native/extend-expect' to your test file
Add: import { toHaveStyle } from '#testing-library/jest-native/dist/to-have-style'
Add: expect.extend({toHaveStyle})
Finally, you have the toHaveStyle for your expect
Sample code:
/**
* #format
*/
import 'react-native';
import '#testing-library/jest-native/extend-expect';
import React from 'react';
import App from '../App';
import {render, screen} from '#testing-library/react-native';
import { toHaveStyle } from '#testing-library/jest-native/dist/to-have-style';
expect.extend({toHaveStyle})
it('renders correctly', () => {
render(<App/>);
const text = screen.getByTestId('Sample Text')
expect(text).not.toBeNull();
const button = screen.getByTestId('Sample Button')
expect(button).not.toBeNull();
expect(button).toHaveStyle({
backgroundColor: 'transparent'
})
});
install jest-styled-components
npm i -D install jest-styled-components
then use .toHaveStyleRule
Example:
import React from 'react';
import { render } from 'react-testing-library';
import Button from '../Button';
import 'jest-styled-components';
describe('<Button />', () => {
it('should render text', () => {
const { getByText } = render(<Button text="Button" />);
expect(getByText('Button')).not.toBeNull();
});
it('should have correct style with background color', () => {
const { getByText } = render(<Button text="Button" color="#fff" />);
expect(getByText('Button')).toHaveStyleRule('background', '#fff');
});
});

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

Typescript, Jest and i18next: Can't see text in React component

I am testing a React component that uses i18next for internationalization.
The component:
import * as React from "react";
import { t } from "i18next";
export function Hello(_props) {
return <div className="widget-header">
{t("Hello, world!")}
</div>;
}
The test:
import * as React from "react";
import { render } from "enzyme";
import { Hello } from "./hello";
describe("<Hello />", () => {
it("says hi", () => {
let hi = render(<Hello />);
// FAILS!
// Expected "" to contain "Hello"
expect(hi.text()).toContain("Hello");
});
})
My suspicion is that Jest is stubbing i18next.t() to return undefined rather than "Hello, world!", but I am unsure of that.
I have tried to unmock("i18next") without any luck.
How do I write tests for i18next components in Jest?
UPDATE: I was using Typescript as my compiler. It appears that there is a hoisting issue with the loader I use for Typescript (ES6 hoists imports, jest.unmock is not- Babel users have a plugin to handle this).
Not sure why its not working but you can just mock put i18next like this:
jest.mock('i18next', () => ({
t: (i) => i
}))

Resources