expect().to.have. returns undefined error - jestjs

Per the enzyme docs here the following stanza should find a selector by ID:
it('Should render the Select Vehicle entry', () => {
let component = shallow(<VehicleMenu {...initialState} />);
expect(component.find("#vehMenuSelect")).to.have.lengthOf(1);
});
But the .to.have.[...] method never works for me anywhere in my code, and always returns:
TypeError: Cannot read property 'have' of undefined
no matter which selector type I use (in this case find).
This works, and is what I have been using:
it('Should render the Select Vehicle entry', () => {
let component = shallow(<VehicleMenu {...initialState} />);
expect(component.find("#vehMenuSelect").length).toBe(1);
});
.toBe() always works. Why do I get that error when using the methods described in the current enzyme docs? THis is with enzyme 3.9.0 and enzyme-adapter-react-16 1.12.1.

The example from the docs of enzyme is not using jest. You should follow the docs of jest. Change it to toHaveLength instead of to.have.length

Related

While writing Jest unit test case getting error as TypeError: Cannot read property 'the' of undefined

When trying to write unit test case getting error TypeError: Cannot read property 'the' of undefined while rendering component with testing library.
MapChart.ts
import { ComposableMap, Geographies } from "react-simple-maps";
const geoUrl = "https://raw.githubusercontent.com/deldersveld/topojson/master/world-countries.json"
const MapChart=()=>{
<ComposableMap projection="geoAzimuthalEqualArea">
<Geographies geography={geoUrl}>
{({ geographies, borders, outline }) => {...}}
</Geographies>
</ComposableMap>
}
MapChart.ts
import { render, screen } from '#testing-library/react';
import MapChart from "./MapChart.ts";
test('Testing map chart',()=>{
render(<MapChart />);
})
Even tried to mock the react-simple-maps library after that it resolving error but it not covering whole component code, not sure how to mock it properly. Please assist here.

How to mock HMSLocation with jest

I'm trying to mock the #hmscore/react-native-hms-location with jest. The function that one of my providers uses is HMSLocation.FusedLocation.Native.hasPermission(), but in one of my test I always get the following:
TypeError: Cannot read property 'Native' of undefined at call (C:\laragon\www\qmy-project\providers\LocationProvider.js:65:57)
I've tried to mock all the Library like this:
jest.mock('#hmscore/react-native-hms-location');
Even like this another way:
jest.mock('#hmscore/react-native-hms-location', () => {
const original = jest.requireActual('#hmscore/react-native-hms-location');
return original;
});
Always is the same. Any help please?

How to mock fetch call inside of childĀ“s componentDidMount with Jest/Enzyme [duplicate]

I would like to test a small React web app where I use the global fetch method.
I tried to mock fetch in this way:
global.fetch = jest.spyOn(global, 'fetch').mockImplementation(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
... but the mock seems to be ignored, while the built-in fetch seems to be used: Error: connect ECONNREFUSED 127.0.0.1:80 ... looks like a failed call to the built-in fetch.
I then tried to use jest.fn instead of jest.spyOn:
global.fetch = jest.fn(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
... and was surprised to see a different error. Now the mock seems to be taken into consideration, but at the same time is not working correctly:
TypeError: Cannot read property 'then' of undefined
8 | this.updateTypes = this.props.updateTypes;
9 | this.updateTimeline = this.props.updateTimeline;
> 10 | fetch('/timeline/tags')
| ^
11 | .then(res => res.json())
12 | .then(tags => tags.map(tag => <option value={tag} key={tag} />))
13 | .then(options => options.sort((a, b) => a.key.localeCompare(b.key)))
I find the documentation of Jest and React Testing Library a bit confusing, honestly. What might be the problem with what I am doing?
Edit
The React component I am trying to test is called "App", was generated with Create React App, and was changed to include a call to fetch. I can gladly provide the code for this component, but I believe that the problem lies in the tests.
At the beginning of my App.test.js file, I import React from 'react';, then import { render, fireEvent, waitFor, screen } from '#testing-library/react';, and finally import App from './App';. I subsequently attempt to mock fetch in one of the ways I described, and then declare the following test:
test('renders a list of items, upon request', async () => {
const app = render(<App />);
fireEvent.click(screen.getByText('Update'));
await waitFor(() => screen.getByRole('list'));
expect(screen.getByRole('list')).toBeInTheDocument();
expect(screen.getByRole('list')).toHaveClass('Timeline');
});
Finally, I end my test file with global.fetch.mockRestore();.
That there's ECONNREFUSED error instead of fetch is not defined means that fetch has been polyfilled. It's not a part of JSDOM and isn't polyfilled by Jest itself but is specific to current setup. In this case the polyfill is provided by create-react-app.
It's always preferable to mock existing global function with jest.spyOn and not by assigning them as global properties, this allows Jest to do a cleanup. A thing like global.fetch = jest.spyOn(global, 'fetch') should never be done because this prevents fetch from being restored. This can explain TypeError: Cannot read property 'then' of undefined error for seemingly correctly mocked function.
A correct and safe way to mock globals is to mock them before each test and restore after each test:
beforeEach(() => {
jest.spyOn(global, 'fetch').mockResolvedValue({
json: jest.fn().mockResolvedValue(mockResponse)
})
});
afterEach(() => {
jest.restoreAllMocks();
});
There should be no other modifications to global.fetch in order for a mock to work correctly.
A preferable way to restore mocks and spies is to use configuration option instead of jest.restoreAllMocks because not doing this may result in accidental test cross-contamination which is never desirable.
Another reason for TypeError: Cannot read property 'then' of undefined error to appear is that Jest incorrectly points at fetch line, and the error actually refers to another line. This can happen if source maps don't work correctly. If fetch is mocked correctly and there are other then in the same component, it's a plausible explanation for the error.

React-testing-library and <Link> Element type is invalid: expected a string or a class/function but got: undefined

I'm using react-testing-library to test a simple component which has a nested react-router-dom's <Link> inside of it and I am getting this error:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I solved it by mocking the Link:
jest.mock('react-router-dom', () => ({
Link: jest.fn().mockImplementation(({ children }) => {
return children;
}),
}));
That way I can test my component normally:
test('render MyComponent with <Link>', async () => {
const myListOfLinks = mockLinks();
render(<MyComponent parents={myListOfLinks} />);
const links = await screen.findByTestId('my-links');
expect(MyComponent).toBeInTheDocument();
});
I had similar issue with Link component being undefined. In our case it was caused by existing jest mock. There was a file in our codebase under __mocks__/react-router-dom.js which didn't provide an implementation for Link. So all other tests were using mocked implmentation of react-router-dom module. Jest uses convention for automatic mocking of modules. Removing this mock solved the issue

How i can mock Reselect functions with jest?

I try to test my saga and i have some problems with testing select.
I want to mock createSelector from reselect, but i can't do this, because i have this error:
Cannot read property \'module\' of undefined
my reselect:
//R - is ramda
export const selectFilters = createSelector(R.path(['notification', 'filters']), (filters) => filters)
my saga:
//module gives me error because selectFilters returns undefined
const {module, orderByDate} = yield select(selectors.selectFilters())
You have to pass the reference to of the selector the the select effect. In your saga, you are actually calling the selector, and then passing the return value. If you do it properly, you don't have to mock the selector.
Modify your code like this to fix the error:
const {module, orderByDate} = yield select(selectors.selectFilters)

Resources