我不熟悉单元测试。
我应该为一个文件创建单元测试,该文件使用API获取数据,然后将其显示在MaterialTable中,并对页面使用TablePagination(来自MaterialUI)。
以下代码供参考:文章源自玩技e族-https://www.playezu.com/193632.html
import React, { useState, useEffect } from 'react';
import clsx from 'clsx';
import { useHistory } from 'react-router-dom';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/styles';
import MaterialTable from 'material-table';
import {
MuiThemeProvider,
createTheme,
TablePagination,
} from '@material-ui/core';
import UserModel from '../../../models/UserModel';
const useStyles = makeStyles((theme) => ({
root: {},
content: {
padding: 0,
},
inner: {
minWidth: 800,
},
statusContainer: {
display: 'flex',
alignItems: 'center',
},
status: {
marginRight: theme.spacing(1),
},
actions: {
justifyContent: 'flex-end',
},
}));
const VehicleTypesData = (props) => {
const [vehicleTypesData, setVehicleTypesData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
var [paramObj, setParamObj] = useState({
const [params, setParams] = useState({
page: 1,
offset: 0,
const numberOfVehicleTypes = Object.keys(vehicleTypesData).length;
const ROWS_PER_PAGE = 10;
const columnDescription = [
{ title: 'Name', field: 'name' },
{
title: 'Capacity (Volume)',
field: 'capacity',
type: 'numeric',
align: 'left',
emptyValue: () => <>-</>,
},
{ title: 'Weight', field: 'weight' },
];
const fetchDataFromAPI = async (paramObj, newOffset, newPage) => {
setIsLoading(true);
UserModel.getInstance().getVehicleTypes(
paramObj,
async (data) => {
let vehicleTypesArray = [];
await data.forEach((obj) => {
vehicleTypesArray.push({
id: obj.id,
title: obj.name,
capacity: obj.capacity,
weight: obj.weight,
setVehicleTypesData(vehicleTypesArray);
setIsLoading(false);
newPage && setParams({ ...params, offset: newOffset, page: newPage
},
(err) => {
setIsLoading(false);
},
);
};
const handleNextPage = async () => {
const newOffset = params.offset + 20;
let newParamObj = { ...paramObj };
newParamObj = { ...newParamObj, offset: newOffset };
setParamObj(newParamObj);
const newPage = params.page + 1;
setIsLoading(true);
fetchDataFromAPI(newParamObj, newOffset, newPage);
};
const handlePreviousPage = async () => {
if (params.offset > 0) {
const newOffset = params.offset - 20;
var newParamObj = { ...paramObj, offset: newOffset };
newParamObj = { ...newParamObj, page: newPage };
setParamObj(newParamObj);
const newPage = params.page - 1;
setIsLoading(true);
fetchDataFromAPI(newParamObj, newOffset, newPage);
}
};
const filterChange = (data) => {
if (params.page !== 1) {
setParams({
...params,
page: 1,
offset: 0,
}
let paramObj = {};
let newParamobj = { ...paramObj };
data.forEach((x) => {
newParamobj = {
...newParamobj,
[x.column.searchKey]: x.value.toLowerCase(),
};
setIsLoading(true);
setParamObj(newParamobj);
fetchDataFromAPI(newParamobj);
};
useEffect(() => {
fetchDataFromAPI();
}, []);
let history = useHistory();
const classes = useStyles();
const { className, ...rest } = props;
const theme = createTheme({
typography: {
fontFamily: 'Nunito Sans, Roboto, sans-serif',
},
return (
<MuiThemeProvider theme={theme}>
<MaterialTable
title="Vehicle Types"
columns={columnDescription}
data={vehicleTypesData}
isLoading={isLoading}
onFilterChange={filterChange}
className={clsx(classes.root, className)}
editable={
{
}
}
options={{
search: false,
paging: false,
debounceInterval: 1000,
maxBodyHeight: 'calc(100vh - 285px)',
headerStyle: {
paddingTop: 0,
paddingBottom: 0,
},
}}
actions={[
{
icon: 'add',
tooltip: 'Add Vehicle Type',
isFreeAction: true,
onClick: () => {
},
},
{
icon: 'edit',
tooltip: 'Edit',
onClick: (event, data) => {
},
},
{
icon: 'delete',
tooltip: 'Delete',
onClick: (event, data) => {
},
},
]}
/>
<TablePagination
component="div"
count={-1}
rowsPerPage={ROWS_PER_PAGE}
rowsPerPageOptions={[ROWS_PER_PAGE]}
page={params.page}
backIconButtonProps={{
'aria-label': 'Previous Page',
onClick: handlePreviousPage,
disabled: isLoading || params.page === 1,
}}
nextIconButtonProps={{
'aria-label': 'Next Page',
onClick: handleNextPage,
disabled: isLoading || numberOfVehicleTypes <= ROWS_PER_PAGE,
}}
labelDisplayedRows={() => {
return `Page ${params.page}`;
}}
/>
</MuiThemeProvider>
);
};
VehicleTypesData.propTypes = {
className: PropTypes.string,
};
export default VehicleTypesData;
相当简单的组件,这是我到目前为止得到的,这只是一个模拟API获取的尝试文章源自玩技e族-https://www.playezu.com/193632.html
import { render, screen } from '@testing-library/react';
import { async } from 'validate.js';
import VehicleTypesData from './component/index';
describe('Vehicle Types Component', () => {
test('renders table data if request succeeds', async () => {
window.fetch = jest.fn();
window.fetch.mockResolvedValueOnce({
json: async () => [
{ id: '1', name: 'Pickup', capacity: '1000', weight: '3000 kg' },
],
render(<VehicleTypesData />);
软件测试软件文章源自玩技e族-https://www.playezu.com/193632.html 文章源自玩技e族-https://www.playezu.com/193632.html
评论