expect(jest.fn())[.not].toHaveBeenCalled() error - reactjs

I'm using Enzyme/Jest to write a test for a function on my component that is triggered through an onClick of a material's menu icon. The function is passed as props to the component. When writing test, it gives me error on simulating click.
import React from 'react';
import scssstyles from './ToggleSideNavComponent.scss';
class ToggleSideNavComponent extends React.Component {
render() {
return (
<a
id="toggle_sidebar_btn"
className={scssstyles.menuIcon}
onClick={this.props.handleSideNavToggle}
>
<i id="menu" className="material-icons menu-icon" style={{fontSize:30}}>menu</i>
</a>
);
}
}
module.exports = ToggleSideNavComponent;
TEST
import expect from 'expect';
import React from 'react';
import {mount, shallow} from 'enzyme';
import ToggleSideNavComponent from './ToggleSideNavComponent';
import sinon from 'sinon';
function setup() {
const props = {
handleSideNavToggle: sinon.spy()
};
return {
props: props,
wrapper: shallow(<ToggleSideNavComponent {...props} />)
};
}
describe('ToggleSideNavComponent', () => {
it('should have menu icon', () => {
const component = setup();
expect(component.wrapper.find('a #menu').length).toBe(1);
component.wrapper.find('#toggle_sidebar_btn #menu').simulate('click');
expect(component.props.handleSideNavToggle).toHaveBeenCalled();
});
});
error :
ToggleSideNavComponent › should have menu icon
expect(jest.fn())[.not].toHaveBeenCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function proxy]
at Object.<anonymous> (src/components/app/Header/NavLeftList/ToggleSideNavComponent/ToggleSideNavComponent.spec.js:25:94)
at new Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

If you're using Jest, you should use Jest's spies, rather than Sinon.
const props = {
handleSideNavToggle: jest.fn()
};

I've tried your code but changed shallow rendering to full DOM rendering using mount and everything works fine:
import React from 'react';
import {shallow, mount} from 'enzyme';
import ToggleSideNavComponent from './ToggleSideNavComponent';
function setup() {
const props = {
handleSideNavToggle: jest.fn()
};
return {
props: props,
wrapper: mount(<ToggleSideNavComponent {...props} />)
};
}
describe('ToggleSideNavComponent', () => {
it('should have menu icon', () => {
const component = setup();
expect(component.wrapper.find('a #menu').length).toBe(1);
component.wrapper.find('#toggle_sidebar_btn #menu').simulate('click');
expect(component.props.handleSideNavToggle).toHaveBeenCalled();
component.wrapper.unmount(); // don't forget to use unmount() after mounting
});
});
seems like there is a problem accessing props when using shallow rendering
If you only want to test the behavior of the handleSideNavToggle function (just unit test this function) then I don't recommend doing it using simulate because you don't need to test React's event wiring nor the browser's, instead you could have shallow rendered the parent component which provides this prop function to your component ToggleSideNavComponent and call this method using suitable arguments and assert results, for example:
describe('ToggleSideNavComponentParent', () => {
it('test parent component function', () => {
const wrapper = shallow(<ToggleSideNavComponentParent/>);
const instance = wrapper.instance();
let e = prepareSuitableEventObject();
instance.handleSideNavToggle(e);
// do your assertions here
});
});
function prepareSuitableEventObject() {
// construct an object and return it
}

Related

Problems testing a Redux + React app with enzyme:

I have this component
import React, { useEffect } from 'react';
import './App.css';
import { connect } from 'react-redux';
import { CircularProgress } from '#material-ui/core';
import { loadPhones } from './redux/actions/actions.js';
import TablePhones from './Table.js';
const mapStateToProps = (state) => state;
function mapDispatchToProps(dispatch) {
return {
loadPhones: () => {
dispatch(loadPhones());
},
};
}
export function App(props) {
useEffect(() => {
props.loadPhones();
}, []);
if (props.phones.data) {
return (
<div className="App">
<div className="introductoryNav">Phones</div>
<TablePhones phones={props.phones.data} />
</div>
);
}
return (
<div className="gridLoadingContainer">
<CircularProgress color="secondary" iconStyle="width: 1000, height:1000" />
<p className="loadingText1">Loading...</p>
</div>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
For whom ive written
import React from 'react';
import { render } from '#testing-library/react';
import { Provider } from "react-redux";
import App from './App';
import { shallow, mount } from "enzyme";
import configureMockStore from "redux-mock-store";
const mockStore = configureMockStore();
const store = mockStore({});
describe('App comp testing', () => {
it("should render without throwing an error", () => {
const app = mount(
<Provider store={store}>
<App />
</Provider>
).dive()
expect(app.find('.introductoryNav').text()).toContain("Phones");
});
})
But that test keeps failing
ypeError: Cannot read property 'data' of undefined
I also tried importing App as {App} instead and using shallow testing, but no luck. It gives the same erros, so im left without access to the context, and I cant keep doing my tests
How can I solve this?
You could use the non-default export of your component here and shallow render test if you pass your component the props and don't try to mock the store (if I recall correctly).
I was thinking something like this might work, tesing the "pure" non-store connected version of the component. This seems to be a popular answer for this question as this was asked (in a different way) before here:
import React from 'react';
import { App } from './App';
import { shallow } from "enzyme";
// useful function that is reusable for desturcturing the returned
// wrapper and object of props inside of beforeAll etc...
const setupFunc = overrideProps => {
const props = {
phones: {
...phones, // replace with a mock example of a render of props.phones
data: {
...phoneData // replace with a mock example of a render of props.phones.data
},
},
loadPhones: jest.fn()
};
const wrapper = shallow(<App {...props} />);
return {
wrapper,
props
};
};
// this is just the way I personally write my inital describe, I find it the easiest way
// to describe the component being rendered. (alot of the things below will be opinios on test improvements as well).
describe('<App />', () => {
describe('When the component has intially rendered' () => {
beforeAll(() => {
const { props } = setupFunc();
});
it ('should call loadPhones after the component has initially rendered, () => {
expect(props.loadPhones).toHaveBeenCalled();
});
});
describe('When it renders WITH props present', () => {
// we should use describes to section our tests as per how the code is written
// 1. when it renders with the props present in the component
// 2. when it renders without the props
beforeAll(() => {
const { wrapper, props } = setupFunc();
});
// "render without throwing an error" sounds quite broad or more like
// how you would "describe" how it rendered before testing something
// inside of the render. We want to have our "it" represent what we're
// actually testing; that introductoryNave has rendered with text.
it("should render an introductoryNav with text", () => {
// toContain is a bit broad, toBe would be more specific
expect(wrapper.find('.introductoryNav').text()).toBe("Phones");
});
it("should render a TablePhones component with data from props", () => {
// iirc toEqual should work here, you might need toStrictEqual though.
expect(wrapper.find('TablePhones').prop('phones')).toEqual(props.phones);
});
});
describe('When it renders WITHOUT props present', () => {
it("should render with some loading components", () => {
expect(wrapper.find('.gridLoadingContainer').exists()).toBeTruthy();
expect(wrapper.find('CircularProgress').exists()).toBeTruthy();
expect(wrapper.find('.loadingText1').exists()).toBeTruthy();
});
});
});

How can i test with Enzyme+Mocha method call inside Component

Cannot figure out how to test a component method with enzyme + mocha + sinon. I want to test if component calls method loadPosts on button click.
import React from 'react';
import { configure, mount} from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import { Posts } from '../Components/Posts';
import sinon from 'sinon';
configure({ adapter: new Adapter() });
describe('Posts', () => {
let wrapper;
let inst;
beforeEach(() => {
wrapper = mount(<Posts />);
inst = wrapper.instance();
sinon.spy(inst, 'loadPosts');
wrapper.find('button').simulate('click');
});
it('should load posts on button click', () => {
wrapper.update();
expect(inst.loadPosts).to.have.property('callCount', 1);
});
it('should set `loading` to true', () => {
expect(wrapper.state('loading')).to.equal(true);
});
});
And here is my component:
import React, {Component} from 'react';
import axios from 'axios';
export class Posts extends Component {
state = {
posts: null,
loading: false
}
componentDidMount() {}
loadPosts = () => {
this.setState({loading: true}, () => {
axios.get('https://jsonplaceholder.typicode.com/todos')
.then( d => this.setState({
posts: d.data
}));
});
}
render() {
return (<div>
<h4>I am posts</h4>
<button onClick= {this.loadPosts}>Load posts</button>
</div>);
}
}
But my test fails with error: Exception error: expected [Function] to have property 'callCount' of 1 but got 0
The onClick of your button gets bound directly to whatever this.loadPosts is when the component renders.
When you replace loadPosts with the spy, it doesn't have any effect on the currently rendered button so onClick doesn't call your spy.
The two options for fixing it are to call this.loadPosts using an arrow function like this:
<button onClick={() => this.loadPosts()}>Load posts</button>
...so that when onClick gets called it calls whatever this.loadPosts is currently set to.
The other option is to force a re-render after you create your spy so onClick gets bound to your spy instead of the original function.

Props aren't passing inside component in test cases written with Jest and Enzyme

This is my test case
import React from 'react';
import { mount } from 'enzyme';
import CustomForm from '../index';
describe('Custom Form mount testing', () => {
let props;
let mountedCustomForm;
beforeEach(() => {
props = {
nav_module_id: 'null',
};
mountedCustomForm = undefined;
});
const customform = () => {
if (!mountedCustomForm) {
mountedCustomForm = mount(
<CustomForm {...props} />
);
}
return mountedCustomForm;
};
it('always renders a div', () => {
const divs = customform().find('div');
console.log(divs);
});
});
Whenever I run the test case using yarn test. It gives the following error TypeError: Cannot read property 'nav_module_id' of undefined.
I have already placed console at multiple places in order to see the value of props. It is getting set. But it couldn't just pass through the components and give the error mentioned above.
Any help would be appreciated been stuck for almost 2-3 days now.
You have to wrap the component that you want to test in beforeEach method such that it becomes available for all the 'it' blocks, and also you have to take the mocked props that you think you are getting into the original component.
import React from 'react'
import {expect} from 'chai'
import {shallow} from 'enzyme'
import sinon from 'sinon'
import {Map} from 'immutable'
import {ClusterToggle} from '../../../src/MapView/components/ClusterToggle'
describe('component tests for ClusterToggle', () => {
let dummydata
let wrapper
let props
beforeEach(() => {
dummydata = {
showClusters: true,
toggleClustering: () => {}
}
wrapper = shallow(<ClusterToggle {...dummydata} />)
props = wrapper.props()
})
describe(`ClusterToggle component tests`, () => {
it(`1. makes sure that component exists`, () => {
expect(wrapper).to.exist
})
it('2. makes sure that cluster toggle comp has input and label', () => {
expect(wrapper.find('input').length).to.eql(1)
expect(wrapper.find('label').length).to.eql(1)
})
it('3. simulating onChange for the input element', () => {
const spy = sinon.spy()
const hct = sinon.spy()
hct(wrapper.props(), 'toggleClustering')
spy(wrapper.instance(), 'handleClusterToggle')
wrapper.find('input').simulate('change')
expect(spy.calledOnce).to.eql(true)
expect(hct.calledOnce).to.eql(true)
})
})
})

How to test function that passed from mapDispatchToProps (React/Redux/Enzyme/Jest)

I want to test that function passed from mapDispatchToProps was invoked when button clicking is simulated.
How to test that function which passed from mapDispatchToProps is invoked?
I tried to pass a mocked function by props, but it doesn't work. Any help will be appreciated.
Here below my fake class code and test example.
My component
// All required imports
class App extends React.Component<Props> {
render() {
const { onClick } = this.props;
return (
<>
<h1>Form</h1>
<input />
<button onClick={() => onClick()} />
</>
);
}
}
const mapStateToProps = (state) => {
return {
state
};
};
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => dispatch(actions.onClick())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
My test file
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16/build/index';
import jsdom from 'jsdom';
import React from 'react';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import ConnectedApp, { App } from './App';
function setUpDomEnvironment() {
const { JSDOM } = jsdom;
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/' });
const { window } = dom;
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
}
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
setUpDomEnvironment();
configure({ adapter: new Adapter() });
const mockStore = configureMockStore();
describe('App', () => {
describe('When App connected to store', () => {
describe('When button clicked', () => {
it('should not crush after click on login button', () => {
const onClick = jest.fn()
const store = mockStore(initialStates[1]);
const wrapper = mount(
<Provider store={store}>
<ConnectedApp />
</Provider>);
wrapper.find('button').simulate('click');
??? how to test that function passed from mapDispatchToProps was fired?
});
});
});
});
I recommend following the approach described in the docs and export the connected component as the default export for use in the application, and export the component itself as a named export for testing.
For the code above export the App class and test the click like this:
import * as React from 'react';
import { shallow } from 'enzyme';
import { App } from './code';
describe('App', () => {
it('should call props.onClick() when button is clicked', () => {
const onClick = jest.fn();
const wrapper = shallow(<App onClick={onClick} />);
wrapper.find('button').simulate('click');
expect(onClick).toHaveBeenCalledTimes(1);
});
});
shallow provides everything that is needed for testing the component itself. (shallow even calls React lifecycle methods as of Enzyme v3)
As you have found, to do a full rendering of the component requires a mock redux store and wrapping the component in a Provider. Besides adding a lot of complexity, this approach also ends up testing the mock store and all child components during the component unit tests.
I have found it much more effective to directly test the component, and to export and directly test mapStateToProps() and mapDispatchToProps() which is very easy since they should be pure functions.
The mapDispatchToProps() in the code above can be tested like this:
describe('mapDispatchToProps', () => {
it('should dispatch actions.onClick() when onClick() is called', () => {
const dispatch = jest.fn();
const props = mapDispatchToProps(dispatch);
props.onClick();
expect(dispatch).toHaveBeenCalledWith(actions.onClick());
});
});
This approach makes unit testing the component very simple since you can pass the component props directly, and makes it very simple to test that the component will be handed the correct props by the pure functions (or objects) passed to connect().
This ensures that the unit tests are simple and targeted. Testing that connect() and redux are working properly with the component and all of its child components in a full DOM rendering can be done in the e2e tests.

Testing Typescript React Component context with enzyme

I have a React Component in Typescript something like this
import * as React from 'react';
import * as PropTypes from 'prop-types';
export class MyComponent extends React.Component<{}, {}> {
context = {
callBack: Function
}
static contextTypes = {
callBack: React.PropTypes.Func
};
render() {
return (
<button onClick={this.callContextCallback}>Call Context</button>
);
}
callContextCallback = () => {
this.context.callBack();
}
}
And I have written my tests for the Component
import { mount, shallow } from 'enzyme'
import * as React from "react"
import { MyComponent } from "./MyComponent"
describe(`<MyComponent />`, () => {
let callBackMock = jest.fn()
beforeEach(() => {
wrapper = mount(
<MyComponent />, {
context: {
callBack: callBackMock
}
}
)
})
it(`should call context Callback on clicking button`, () => {
wrapper.find('button').simulate('click')
expect(callBackMock).toHaveBeenCalledTimes(1)
})
})
when I run my tests, The test fails with function not being called.
I even tried mocking spying on the callContextCalback function
it(`should call context Callback on clicking button`, () => {
let instance = wrapper.instance()
const spy = jest.spyOn(instance, 'callContextCallback')
instance.forceUpdate();
wrapper.find('button').simulate('click')
expect(spy).toHaveBeenCalledTimes(1)
})
and on running the test I get this error
Error: Uncaught [TypeError: Cannot read property 'context' of undefined]
TypeError: Cannot read property 'context' of undefined
How do I test the context callBack function?
The issue is resolved with help from the enzyme team.
Please refer to this Github Issue to know more about the solution.

Resources