How to use updateRequest method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

index.js

Source: index.js Github

copy
1import { Box, Button, List, TextField, Typography } from '@material-ui/core';
2import React, { useEffect } from 'react';
3import Wrapper from '../../../layouts/wrapper';
4import useStyles from './styles';
5import { connect } from 'react-redux';
6import { fetchAllOptionStatus, fetchAllOptionCategory, fetchAllOptionAdmin, fetchAllOptionPriority } from '../../../store/actions/optionAction';
7import { requestDetail, updateRequest } from '../../../store/actions/requestAction';
8import * as Yup from 'yup';
9import { useFormik } from 'formik';
10import Toast from '../../../components/toast';
11import ItemAddRequest from '../../../components/item-add-request';
12import { useHistory } from 'react-router';
13import { KeyboardReturnOutlined, PublishOutlined } from '@material-ui/icons';
14import formatDate from '../../../helpers/formatDate';
15import { STATUS_ADMIN_ACTIVE, STATUS_CATE_ENABLE } from '../../../constants';
16
17const UpdateRequest = (props) => {
18  const classes = useStyles();
19  const history = useHistory();
20  const { fetchAllStatus, fetchAllCategory, fetchAllAdmin, fetchAllPriority, fetchRequestDetail } = props;
21
22  useEffect(() => {
23    fetchAllStatus();
24    fetchAllCategory({ status: STATUS_CATE_ENABLE });
25    fetchAllAdmin({ status: STATUS_ADMIN_ACTIVE });
26    fetchAllPriority();
27    fetchRequestDetail(props.match.params.id);
28  }, [props.match.params.id, fetchAllStatus, fetchAllCategory, fetchAllAdmin, fetchAllPriority, fetchRequestDetail]);
29
30  const updateRequest = useFormik({
31    initialValues: {
32      name: props.requestDetail.name,
33      content: props.requestDetail.content,
34      status_id: props.requestDetail.status_id,
35      assign_id: props.requestDetail.assign_id,
36      category_id: props.requestDetail.category_id,
37      due_date: props.requestDetail.due_date,
38      priority_id: props.requestDetail.priority_id,
39    },
40    enableReinitialize: true,
41    validationSchema: Yup.object({
42      name: Yup.string()
43        .required("Required !"),
44      content: Yup.string()
45        .required("Required !"),
46      assign_id: Yup.number()
47        .required("Required !"),
48      category_id: Yup.number()
49        .required("Required !"),
50      priority_id: Yup.number()
51        .required('Required !'),
52      due_date: Yup.date()
53        .min(formatDate(new Date()), 'Must be greater or equals than today')
54        .required("Required !")
55    }),
56    onSubmit: (values) => {
57      props.fetchUpdateRequest(props.match.params.id, values);
58    }
59  })
60
61  return (
62    <Wrapper >
63      <div className={classes.root}>
64        <form>
65          <div className={classes.header}>
66            <Typography
67              variant="h5"
68              className={classes.title}
69            >
70              Update request
71            </Typography>
72            <div className={classes.grow} />
73            <Button
74              color="primary"
75              variant="contained"
76              type="submit"
77              onClick={updateRequest.handleSubmit}
78              startIcon={<PublishOutlined />}
79            >
80              Update
81            </Button>
82            <Button
83              variant="contained"
84              className={classes.return}
85              startIcon={<KeyboardReturnOutlined />}
86              onClick={() => history.goBack()}
87            >
88              Return
89            </Button>
90          </div>
91          <TextField
92            className={classes.requestTitle}
93            placeholder={"Title..."}
94            variant="outlined"
95            type="text"
96            FormHelperTextProps={{
97              className: classes.helperText
98            }}
99            name="name"
100            value={updateRequest.values.name || ''}
101            onChange={updateRequest.handleChange}
102            helperText={updateRequest.errors.name}
103          />
104          <Box
105            className={classes.box}
106          >
107            <TextField
108              variant="outlined"
109              fullWidth
110              multiline={true}
111              rows={5}
112              FormHelperTextProps={{
113                className: classes.helperText
114              }}
115              placeholder={"Add a description..."}
116              name="content"
117              value={updateRequest.values.content || ''}
118              onChange={updateRequest.handleChange}
119              helperText={updateRequest.errors.content}
120            />
121            <List
122              className={classes.boxDetail}
123            >
124              <ItemAddRequest
125                label={"Status"}
126                name={"status_id"}
127                select={true}
128                value={updateRequest.values.status_id}
129                handleChange={(value) => updateRequest.setFieldValue('status_id', value)}
130                data={props.statuses}
131                disable={true}
132                error={updateRequest.errors.status_id}
133              />
134              <ItemAddRequest
135                label={"Assign"}
136                name={"assign_id"}
137                select={true}
138                value={updateRequest.values.assign_id}
139                handleChange={(value) => updateRequest.setFieldValue('assign_id', value)}
140                data={props.admins}
141                error={updateRequest.errors.assign_id}
142              />
143              <ItemAddRequest
144                label={"Category"}
145                name={"category_id"}
146                select={true}
147                value={updateRequest.values.category_id}
148                handleChange={(value) => updateRequest.setFieldValue('category_id', value)}
149                data={props.categories}
150                error={updateRequest.errors.category_id}
151              />
152              <ItemAddRequest
153                label={"Due date"}
154                name="due_date"
155                select={false}
156                type={"date"}
157                value={updateRequest.values.due_date}
158                handleChange={(value) => updateRequest.setFieldValue('due_date', value)}
159                error={updateRequest.errors.due_date}
160              />
161              <ItemAddRequest
162                label={"Priority"}
163                name={"priority_id"}
164                select={true}
165                value={updateRequest.values.priority_id}
166                handleChange={(value) => updateRequest.setFieldValue('priority_id', value)}
167                data={props.priorities}
168                error={updateRequest.errors.priority_id}
169              />
170            </List>
171          </Box>
172        </form>
173      </div>
174      <Toast />
175    </Wrapper>
176  )
177}
178
179const mapStateToProps = (state, ownProps) => {
180  return {
181    admins: state.option.admins,
182    statuses: state.option.statuses,
183    categories: state.option.categories,
184    priorities: state.option.priorities,
185    requestDetail: state.request.requestDetail,
186  }
187}
188
189const mapDispatchToProps = (dispatch, ownProps) => {
190  return {
191    fetchAllStatus: () => {
192      dispatch(fetchAllOptionStatus());
193    },
194    fetchAllCategory: (data) => {
195      dispatch(fetchAllOptionCategory(data));
196    },
197    fetchAllAdmin: (data) => {
198      dispatch(fetchAllOptionAdmin(data));
199    },
200    fetchAllPriority: () => {
201      dispatch(fetchAllOptionPriority())
202    },
203    fetchRequestDetail: (id) => {
204      dispatch(requestDetail(id));
205    },
206    fetchUpdateRequest: (requestId, data) => {
207      dispatch(updateRequest(requestId, data));
208    }
209  }
210}
211
212export default connect(mapStateToProps, mapDispatchToProps)(UpdateRequest);
213
Full Screen

UpdateRequest.test.js

Source: UpdateRequest.test.js Github

copy
1const isEqual = require('lodash/isEqual');
2
3const UpdateRequest = require('./UpdateRequest');
4const Update = require('./Update');
5
6const originalFindOneMethod = UpdateRequest.findOne;
7
8let lastUpdateRequestMock;
9
10const findOneMethodMock = (criteria, fields, options) => {
11
12    const areCriteriaValid = isEqual(criteria, {});
13    const areFieldsValid = isEqual(fields, { dateTime: true });
14    const areOptionsValid = isEqual(options, { sort: { _id: -1 } });
15
16    if (areCriteriaValid && areFieldsValid && areOptionsValid) {
17
18        return Promise.resolve(lastUpdateRequestMock);
19    }
20
21    return Promise.resolve('UpdateRequest.findOne called with invalid params');
22};
23
24describe('UpdateRequest.loadNewest', () => {
25
26    beforeEach(() => {
27
28        UpdateRequest.findOne = findOneMethodMock;
29    });
30
31    it('should return a promise', () => {
32
33        expect(UpdateRequest.loadNewest()).toBeInstanceOf(Promise);
34    });
35
36    it('should resolve a promise with ' +
37        'UpdateRequest.findOne (called with proper params) output', async () => {
38
39        expect.assertions(2);
40
41        lastUpdateRequestMock = 'database response';
42
43        expect(await UpdateRequest.loadNewest()).toBe('database response');
44
45        lastUpdateRequestMock = 'another database response';
46
47        expect(await UpdateRequest.loadNewest()).toBe('another database response');
48    });
49
50    afterEach(() => {
51
52        UpdateRequest.find = originalFindOneMethod;
53    });
54});
55
56describe('UpdateRequest.canBeProcessed', () => {
57
58    let lastUpdateMock;
59
60    const originalUpdateFindOneMethod = Update.findOne;
61
62    beforeEach(() => {
63
64        lastUpdateMock = null;
65
66        Update.findOne = (criteria, fields) => {
67
68            if (fields === undefined || isEqual(fields, { dateTime: true })) {
69
70                return Promise.resolve(lastUpdateMock);
71            }
72
73            return Promise.resolve('Update.findOne called with invalid params');
74        };
75
76        UpdateRequest.findOne = findOneMethodMock;
77    });
78
79    it('should return a promise', () => {
80
81        lastUpdateRequestMock = null;
82
83        expect(UpdateRequest.canBeProcessed()).toBeInstanceOf(Promise);
84    });
85
86    it('should resolve a promsie with true if timetable has not been updated yet', async () => {
87
88        expect.assertions(1);
89
90        const result = await UpdateRequest.canBeProcessed();
91
92        expect(result).toBe(true);
93    });
94
95    it('should resolve a promsie with false ' +
96        'if timetable has been updated late enough', async () => {
97
98        expect.assertions(1);
99
100        lastUpdateMock = { dateTime: Date.now() };
101
102        const result = await UpdateRequest.canBeProcessed();
103
104        expect(result).toBe(false);
105    });
106
107    it('should resolve a promsie with true if update has not been requested yet', async () => {
108
109        expect.assertions(1);
110
111        lastUpdateMock = { dateTime: 1000 };
112        lastUpdateRequestMock = null;
113
114        const result = await UpdateRequest.canBeProcessed();
115
116        expect(result).toBe(true);
117    });
118
119    it('should resolve a promsie with true ' +
120        'if update has been requested enough time ago', async () => {
121
122        expect.assertions(1);
123
124        lastUpdateMock = { dateTime: 1000 };
125        lastUpdateRequestMock = { dateTime: 1000 };
126
127        const result = await UpdateRequest.canBeProcessed();
128
129        expect(result).toBe(true);
130    });
131
132    it('should resolve a promsie with false if update has been requested too early', async () => {
133
134        expect.assertions(1);
135
136        lastUpdateMock = { dateTime: 1000 };
137        lastUpdateRequestMock = { dateTime: Date.now() };
138
139        const result = await UpdateRequest.canBeProcessed();
140
141        expect(result).toBe(false);
142    });
143
144    afterEach(() => {
145
146        Update.findOne = originalUpdateFindOneMethod;
147        UpdateRequest.findOne = originalFindOneMethod;
148    });
149});
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)