Testing React components in a Laravel application typically involves using tools like Jest and Enzyme. Laravel Mix makes it easy to integrate these tools into your Laravel project. Here's a step-by-step guide:
Node.js and npm: Ensure Node.js and npm are installed on your machine. You can download and install them from nodejs.org.
Laravel Mix: Laravel Mix simplifies the asset compilation process. It comes pre-installed with Laravel.
bash# Navigate to your Laravel project directory
cd your-laravel-project
# Install Jest and Enzyme
npm install --save-dev jest @babel/preset-env @babel/preset-react babel-jest enzyme enzyme-adapter-react-16
Create a jest.config.js
file in the root of your project with the following content:
javascriptmodule.exports = {
preset: 'jest-preset-laravel',
setupFilesAfterEnv: ['./tests/setupTests.js'],
testMatch: [
'<rootDir>/resources/js/**/__tests__/**/*.js?(x)',
'<rootDir>/resources/js/**/?(*.)+(spec|test).js?(x)',
],
};
Create a babel.config.js
file in the root of your project with the following content:
javascriptmodule.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};
Create a tests/setupTests.js
file with the following content:
javascriptimport Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
Create a sample test file, for example, resources/js/components/__tests__/Example.test.js
:
javascriptimport React from 'react';
import { shallow } from 'enzyme';
import Example from '../Example'; // Replace with the actual path to your component
describe('Example Component', () => {
it('renders without crashing', () => {
shallow(<Example />);
});
});
Add the following scripts to your package.json
file:
json"scripts": {
"test": "jest",
"test:watch": "jest --watch",
}
Now, you can run your tests using:
bashnpm test
Or, to run tests in watch mode:
bashnpm run test:watch
This setup allows you to write and run tests for your React components within your Laravel application. Adjust the paths and configurations according to your project structure and requirements.