📅  最后修改于: 2023-12-03 15:37:48.389000             🧑  作者: Mango
ReactJS 是一款开源的 JavaScript 库,它让你构建用户界面变得更加简单。今天我们将使用 ReactJS 创建一个购物车应用,并为它编写测试用例。
在开始之前,请确保你已经安装了 Node.js 和 npm。然后运行以下命令安装需要的依赖:
npm install react react-dom redux react-redux webpack webpack-dev-server babel-loader babel-core babel-preset-env babel-preset-react enzyme enzyme-adapter-react-16 jest babel-jest --save-dev
我们需要先创建一个基于 ReactJS 的项目。
首先,我们需要创建一个新的目录,并且在该目录下运行 npm init
命令来初始化项目:
mkdir shopping-cart
cd shopping-cart
npm init -y
Webpack 为我们提供了一种模块化的方式来打包我们的代码。执行以下命令来安装 Webpack:
npm install webpack webpack-dev-server --save-dev
在项目根目录中创建一个名为 webpack.config.js
的文件:
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true,
port: 9000
}
};
在 src
目录下创建一个名为 index.js
的文件,并编写以下代码:
import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
const ADD_TO_CART = "ADD_TO_CART";
const REMOVE_FROM_CART = "REMOVE_FROM_CART";
const initialState = {
cartItems: []
};
const cartReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
return {
cartItems: [...state.cartItems, action.payload]
};
case REMOVE_FROM_CART:
return {
cartItems: state.cartItems.filter(item => item.id !== action.payload.id)
};
default:
return state;
}
};
const rootReducer = combineReducers({
cart: cartReducer
});
const store = createStore(rootReducer);
class App extends React.Component {
state = {
products: [
{
id: 1,
title: "Product 1",
price: 10
},
{
id: 2,
title: "Product 2",
price: 20
},
{
id: 3,
title: "Product 3",
price: 30
}
]
};
addToCart = product => {
store.dispatch({
type: ADD_TO_CART,
payload: product
});
};
removeFromCart = product => {
store.dispatch({
type: REMOVE_FROM_CART,
payload: product
});
};
render() {
const cartItems = store.getState().cart.cartItems;
return (
<Provider store={store}>
<div>
<h1>Shopping Cart App</h1>
<ul>
{this.state.products.map(product => (
<li key={product.id}>
<span>{product.title}</span>
<span>{product.price}</span>
<button
disabled={cartItems.find(item => item.id === product.id)}
onClick={() => this.addToCart(product)}
>
Add to cart
</button>
<button
disabled={!cartItems.find(item => item.id === product.id)}
onClick={() => this.removeFromCart(product)}
>
Remove from cart
</button>
</li>
))}
</ul>
<h2>Cart Items</h2>
<ul>
{cartItems.map(item => (
<li key={item.id}>
<span>{item.title}</span>
<span>{item.price}</span>
</li>
))}
</ul>
</div>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
在项目根目录下运行以下命令:
webpack-dev-server --open
然后在浏览器中访问 http://localhost:9000
,你应该可以看到一个简单的购物车应用。
我们已经创建了购物车应用,现在让我们为它编写一些测试用例。
执行以下命令安装 Jest 和 Enzyme:
npm install enzyme enzyme-adapter-react-16 jest babel-jest --save-dev
在项目根目录中创建一个名为 jest.config.js
的文件:
module.exports = {
setupFilesAfterEnv: ["./src/setupTests.js"],
moduleFileExtensions: ["js", "jsx"],
moduleNameMapper: {
"\\.(css|less)$": "identity-obj-proxy"
},
transform: {
"^.+\\.jsx?$": "babel-jest"
},
testEnvironment: "jsdom"
};
在 src
目录下创建一个名为 setupTests.js
的文件:
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });
在 src
目录下创建一个名为 App.test.js
的文件:
import React from "react";
import { shallow } from "enzyme";
import { createStore } from "redux";
import { Provider } from "react-redux";
import App from "./App";
describe("Shopping Cart App", () => {
let store;
let component;
beforeEach(() => {
store = createStore(() => ({ cart: { cartItems: [] } }));
component = shallow(
<Provider store={store}>
<App />
</Provider>
);
});
it("should render the title", () => {
expect(component.find("h1").text()).toEqual("Shopping Cart App");
});
it("should add item to cart", () => {
component
.find("button")
.at(0)
.simulate("click");
expect(store.getState().cart.cartItems.length).toEqual(1);
});
it("should remove item from cart", () => {
store.dispatch({
type: "ADD_TO_CART",
payload: { id: 1, title: "Product 1", price: 10 }
});
component.update();
expect(store.getState().cart.cartItems.length).toEqual(1);
component
.find("button")
.at(1)
.simulate("click");
expect(store.getState().cart.cartItems.length).toEqual(0);
});
});
运行以下命令来执行测试:
npm test
如果一切正常,你应该能够看到测试成功通过的信息。
在本文中,我们学习了如何使用 ReactJS 创建一个购物车应用,并为它编写了测试用例。这个项目还可以进一步扩展,比如使用 React Router 来实现页面跳转等。希望这篇文章对你有所帮助!