Jest mocks in test util - reactjs

I'm using a __mocks__ folder to mock a node_module. Nice.
Example to one of the mocks, that mock 'react-relay': https://gist.github.com/robrichard/ad838e599d828a89978f54faaa2070a8
The file is located as such __mocks__/relay-react.js,
the the mock with be used in my test when jest.mock('react-relay) is executed in the testfile.
However, I have many repos that need that same mock. Is it possible to put the mock in a node_module, so to streamline my tests and do not have to copy/paste the mock everywhere?

This is the best solution so far (as described here: https://github.com/facebook/jest/issues/2726#issuecomment-283100333):
testutils.js
import React, { Component } from 'react';
exports.mockRelay = {
createFragmentContainer: Component => props => <Component {...props} />,
...
// all the named imports you want to mock
};
then in the testfile call
jest.mock('react-relay', () => require('util/testutils').mockRelay)

Related

how can i ise i18n in unit test from react testing library

I'm trying to get translations from i18n files in my unit testing, I've seen other answers but they work with just one i18n file, My problem is that, I have 2 files and the folder structure is like this,
i18n/en/translation.json
i18n/es/translation.json
and translation.json file is written like this
{... "info":"information", "name":"Name", ...}
doesn't have an export default.
and here is my test file,
import React from 'react'
import '#testing-library/jest-dom'
import {render} from '#testing-library/react'
import AddUsers from '../../components/AddUsers'
test('Render OK',()=>{
const menuLinkUp =false
const component =render(
<AddUsers/>
)
component.getByText(" how can i call my i18n?")
})
I'm using react testing library and jest for doing this.
There is a section in the documentation: https://react.i18next.com/misc/testing.
I would probably mock the react-i18next module, as it requires the least amount of changes.
jest.mock('react-i18next', () => ({
// this mock makes sure any components using the translate HoC receive the t function as a prop
withTranslation: () => Component => {
Component.defaultProps = { ...Component.defaultProps, t: () => "" };
return Component;
},
}));
(If you actually want to "inject" the translations: https://react.i18next.com/misc/testing#example-test-using-this-configuration)

How to mock a React Component in the __mocks__ directory with jest?

I have been trying to extract a common mocked component to the mocks folder without success. I am only able to do it with regular JS files, but not with Components.
If I have a module getList as so:
export const getBigger = (a, b) => {
return a >= b ? a : b;
};
I can use it inside my component as so:
export default function App() {
const bigger = getBigger("a", "b");
return (
<div className="App">
<Bigger bigger={bigger} />
</div>
);
}
And I can put the pure js function inside the mocks folder
export const getBigger = jest.fn((p1, p2) => false);
And I can import it in my test without any problems:
import { getBigger as mockedGetBigger } from '../utils';
jest.mock('../utils');
And do my assertions:
expect(mockedGetBigger).toHaveBeenCalledTimes(1);
expect(mockedGetBigger).toHaveBeenCalledWith('a', 'b');
But I can't do the same if I want to mock the Bigger Component, it only works as so:
jest.mock('../Bigger', () => ({
Bigger: jest.fn(() => <>Mocked Bigger Component</>),
}));
But if I extract the function to the mocks folder and I try to use it just as the simple js function I get an error:
import React from 'react';
export const Bigger = jest.fn(() => <>Mocked Bigger Image</>);
And in the test import it and use it as:
import { Bigger as MockedBigger } from '../Bigger';
jest.mock('../Bigger');
I get the following error:
Error: Uncaught [Error: Bigger(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.]
I am not sure what the difference is when jest is importing and mocking in the same step or going to look for the mock function to the mocks folder.
Any ideas?
Somebody else complained about it here: https://github.com/facebook/jest/issues/6935
I made a simple codesandbox to help to understand the problem: https://codesandbox.io/s/mocks-folder-example-oxht3?file=/src/index.js
And here is the guide from jest to put your mocks in the __mocks__ folder
In the end, I found out.
I created a CodeSandbox but as it happens, jest.mock() is not available in CodeSandbox yet...
Anyway my problem was that I was not using the same extension for the real file and its corresponding file in the __mocks__ folder.
Silliest mistake ever!

Enzyme / Jest Error testing component render in React (TS)

I've been having an odd issue with Jest/Enzyme testing on my react typescript app. For some reason it gives a syntax error even though this is following the official documentation, as well as input from several articles.
The Code:
import React from 'react';
import NavbarTop from "../components/navbar";
import { shallow } from 'enzyme';
describe('NavbarTop', () => {
it('renders correctly', () => {
const wrapper = shallow(<NavbarTop />);
expect(wrapper).toMatchSnapshot();
// On the first run of this test, Jest will generate a snapshot file automatically.
});
});
The folder structure. I have a named class and then an index with a default export.
The error log.
Do you have JSX configured for Jest? Looks like you don't have support for JSX in Jest, which probably means this is a configuration issue. Have a look at configuring babel to support JSX in Jest.
Make sure you read this tutorial

Why does Jest snapshot show uglified component name instead of exported name

I've got a (private) npm module that exports several React components. The module is bundled by Webpack and in the generated bundle a reference to one of the components (say Warning) looks like this:
t.d(n,"Warning",function(){return ge})
Then I've got a React project importing this module:
import { Warning } from 'my-custom-module';
...
render() {
return (
<Warning>Lorem ipsum</Warning>
);
}
This all works OK, but when I create a Jest snapshot of the component above, I expect the snapshot to look like
<Warning>Lorem ipsum</Warning>
but it looks like:
<ge>Lorem ipsum</ge>
For some reason Jest takes the minified identifier instead of the exported name of the component. How can I see the component name in the Jest snapshot? I'm unsure if I do need to adjust my Webpack config or the Jest setup...
Since you are referring the uglified version of the 'my-custom-module' it will try to render to the uglified names. However, I assume what you actually you need is to shallowly render your component.
You can use the Enzyme libraries's shallow renderer for this.
//MyAwesomeComponent.js
import { Warning } from 'my-custom-module';
export default class MyAwesomeComponent extends Component{
render(){
return (<Warning>Lorem ipsum</Warning>);
}
}
//MyAwesomeComponent.test.js
import { shallow } from 'enzyme';
import MyAwesomeComponent from './MyAwesomeComponent';
it('renders <MyAwesomeComponent />', () => {
const shallowMyComponent = shallow(<MyComponent />);
expect(shallowMyComponent).toMatchSnapshot()
});
This should show your snapshot as Warning without going a level deeper.

Mock import/module with Jest in React application

I am working on a React application and I want to test one module, let's call it B, that depends on another module, let's call it A.
The scenario could be something like this:
moduleA.js
export function helperFn() {
return { prop1: 10, prop2: 20 };
}
moduleB.js
import React from 'react';
import { helperFn } from '../moduleA';
export class CustomComp extends React.Component {
render() {
const helperObj = helperFn();
return (
<div>{helperObj.prop1}</div>
);
}
}
The core libraries to test my components are Jest and Enzyme. My goal here is to test module B, but I want to test it in isolation and so I want to mock the dependency on moduleA.js.
I know one way would be to inject the helperFn as a prop instead of importing it so during the test I can inject a mock function, but there are modules quite big on this app that have a few dependencies each of them.
Researching a bit I found it is posible to mock a dependecy using Jest, but I tried many things with no success. I tried approaches from this question, also from this post and I have no luck. I also read the Manual Mocks and Mock Functions guides from Jest docs, but I think they are pretty confusing.
I could make it work (i.e. I could mock moduleA.js dependency) using the approach on this post, but I had another problem then. It worked just fine to test moduleB.js, but when I went ahead and test moduleA.js, I had to import moduleA.js in moduleA.test.js and I got the mock while I wanted the real module.
So, I need help to understand how I can mock dependency A in moduleB test file.
I hope I was clear if not let me know and I will add the clarifications you might need.
Thanks in advance !
Indeed you can use jest to mock your dependency. There is some configuration you need to set in order to make it work with import. E.g. configuring babel-jest.
If you already have that configuration then you can mock it like so.
import React from 'react';
import { shallow } from 'enzyme';
import { helperFn } from '../moduleA';
jest.mock('../moduleA');
describe("CustomComp", () => {
it("should render component", () => {
helperFn.mockReturnValueOnce({
prop1: "dummy"
});
const component = shallow(<CustomComp />);
});
You can see a working example here.
I'm using Vue2 and trying to write tests for a Vue component. The Vue component uses a lot of other components that aren't really needed to test.
So for that reason, I created a mock for importing other components like below
jest.mock('#/core/components/UserInput.vue', () => ({
exec: jest.fn(),
}));

Resources