I am new to react and jest. I have been looking everywhere for testing but I cannot find anything that is helpful. This is partially because I am so new to it, I havent a clue where to start. So bear with me, please.
I have an add to cart file which renders a form with a button inside it. The button is another component, so I'm not looking to test it. I have to test the onSubmit function for the form. Any thoughts? References?
Here is my code so far for the test:
describe('AddToCart', () => {
const React = require('react');
const BaseRenderer = require('react/lib/ReactTestUtils');
const Renderer = BaseRenderer.createRenderer();
const ReactTestUtils = require('react-addons-test-utils');
const AddToCart = require('../index.js').BaseAddToCart;
it('Will Submit', () => {
formInstance = ReactTestUtils.renderIntoDocument(<AddToCart product="" quantity=""/>);
expect(ReactTestUtils.Simulate.onSubmit(formInstance)).toBeCalled();
});
});
I'm getting this error:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
Consider using Jest with Enzyme. I think it's good stack for unit testing in react.
Also, I made a sample test that tests onSubmit function in LogIn component.
import React from 'react';
import {shallow} from 'enzyme';
import LogIn from './LogIn';
describe('<LogIn />', () => {
const testValues = {
username: 'FOO',
password: 'BAZ',
handleSubmit: jest.fn(),
};
it('Submit works', () => {
const component = shallow(
<LogIn {...testValues} />
);
component.find('#submitButton').simulate('click');
expect(testValues.handleSubmit).toHaveBeenCalledTimes(1);
expect(testValues.handleSubmit).toBeCalledWith({username: testValues.username, password: testValues.password});
});
});