Testing Axios in Jest - reactjs

I'm new to testing.
I'm trying to test an asynchronous data fetching function but I can't figure out why the test doesn't pass.
I have mocked Axios with jest and gave Axios' get method a mock implementation to resolve a promise.
The error says it can't read the property of name with means the data obj is undefined I reckon.
Here's Yelp.test.js
import Yelp from './Yelp';
import axios from 'axios';
jest.mock('axios');
describe('searchRestaurantsInfo', () => {
test('returns object with restaurant infos', async () => {
const data = {
name: 'Casa Romana',
address: '5 Albion Street',
coordinates: { lat: 52.6322649, lng: -1.1314474 },
city: 'Leicester LE1 6GD',
rating: 4.5,
photos: [
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
],
phone: '+441162541174',
price: '£££',
categories: 'Italian',
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm',
reviews: [
{
id: 'i_Q39aN9hwZzGDUb-IWpYw',
rating: 5,
text:
'Proper Italian restaurant. Not Italian-themed, or serving Italian fusion cuisine, just a place with an Italian owner who makes solid, straightforward...',
time_created: '2014-10-02 03:49:36',
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&hrid=i_Q39aN9hwZzGDUb-IWpYw&utm_campaign=yelp_api_v3&utm_me',
user: {
id: '6tPD46XZSFllvgn2vTh51A',
image_url:
'https://s3-media3.fl.yelpcdn.com/photo/A4Ww6Ks2P9WsALqOFy9cOA/o.jpg',
name: 'Espana S.',
profile_url:
'https://www.yelp.com/user_details?userid=6tPD46XZSFllvgn2vTh51A',
},
},
],
};
axios.get.mockImplementationOnce(() => Promise.resolve(data));
await expect(
Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
).resolves.toEqual(data);
});
});
And Yelp.js
import axios from 'axios';
let YELP_API_KEY = process.env.REACT_APP_YELP_API_KEY;
const Yelp = {
// Provides infos about a single restaurant
async searchRestaurantsInfo(id) {
try {
let response = await axios.get(
`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/${id}`,
{
headers: {
Authorization: `Bearer ${YELP_API_KEY}`,
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
},
}
);
let responseRew = await axios.get(
`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/${id}/reviews`,
{
headers: {
Authorization: `Bearer ${YELP_API_KEY}`,
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
},
}
);
const parameters = {
name: response.data.name,
address: response.data.location.display_address[0],
coordinates: {
lat: response.data.coordinates.latitude,
lng: response.data.coordinates.longitude,
},
city: response.data.location.display_address[1],
rating: response.data.rating,
photos: response.data.photos,
phone: response.data.phone,
price: response.data.price,
categories: response.data.categories[0].title,
url: response.data.url,
reviews: responseRew.data.reviews,
};
console.log({ parameters, id });
return parameters;
} catch (e) {
console.log(e);
return e;
}
}}
The error I get is
searchRestaurantsInfo
× returns array of restaurnats obj (66ms)
● searchRestaurantsInfo › returns array of restaurnats obj
expect(received).resolves.toEqual(expected) // deep equality
- Expected
+ Received
- Object // data object. I removed it from this error message because too long
+ [TypeError: Cannot read property 'name' of undefined]
47 | await expect(
48 | Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
> 49 | ).resolves.toEqual(data);
| ^
50 | });
51 | });
52 |
at Object.toEqual (node_modules/react-scripts/node_modules/expect/build/index.js:202:20)
at Object.<anonymous> (src/helpers/Yelp.test.js:49:16)
console.log src/helpers/Yelp.js:91
TypeError: Cannot read property 'name' of undefined
at Object.searchRestaurantsInfo (C:\Users\Turi\Desktop\project\RestaurantsRedux\src\helpers\Yelp.js:72:29)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Object.<anonymous> (C:\Users\Turi\Desktop\project\RestaurantsRedux\src\helpers\Yelp.test.js:47:5)
Thanks in advance for your help!

There might be a problem with how you wait for the result (possible compilation issue), try writing the test like this.
// note make sure the test() function is async
const result = await Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
expect(result).toEqual(data);

I've managed to find the solution.
Like suggested I had to add another mock since in the function there are two different request.
In addition to that I realised I couldn't use data in both
axios.get.mockImplementationOnce(() => Promise.resolve(data));
and
Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
).resolves.toEqual(data);```
since the function wasn't returning data but an object with some parts from data.
Therefore I created a new object params to be compared with the function returned object.
import Yelp from './Yelp';
import axios from 'axios';
jest.mock('axios');
describe('searchRestaurantsInfo', () => {
test('returns object with restaurant infos', async () => {
const response = {
data: {
name: 'Casa Romana',
location: {
display_address: [
"12 Upper Saint Martin's Lane",
'London WC2H 9FB',
'United Kingdom',
],
},
coordinates: { latitude: 52.6322649, longitude: -1.1314474 },
rating: 4.5,
photos: [
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
],
phone: '+441162541174',
price: '£££',
categories: [{ alias: 'indpak', title: 'Indian' }],
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm',
},
};
const responseRev = {
data: {
reviews: [
{
id: 'i_Q39aN9hwZzGDUb-IWpYw',
rating: 5,
text:
'Proper Italian restaurant. Not Italian-themed, or serving Italian fusion cuisine, just a place with an Italian owner who makes solid, straightforward...',
time_created: '2014-10-02 03:49:36',
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&hrid=i_Q39aN9hwZzGDUb-IWpYw&utm_campaign=yelp_api_v3&utm_me',
user: {
id: '6tPD46XZSFllvgn2vTh51A',
image_url:
'https://s3-media3.fl.yelpcdn.com/photo/A4Ww6Ks2P9WsALqOFy9cOA/o.jpg',
name: 'Espana S.',
profile_url:
'https://www.yelp.com/user_details?userid=6tPD46XZSFllvgn2vTh51A',
},
},
],
},
};
const params = {
name: 'Casa Romana',
address: "12 Upper Saint Martin's Lane",
coordinates: { lat: 52.6322649, lng: -1.1314474 },
city: 'London WC2H 9FB',
rating: 4.5,
photos: [
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
],
phone: '+441162541174',
price: '£££',
categories: 'Indian',
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm',
reviews: [
{
id: 'i_Q39aN9hwZzGDUb-IWpYw',
rating: 5,
text:
'Proper Italian restaurant. Not Italian-themed, or serving Italian fusion cuisine, just a place with an Italian owner who makes solid, straightforward...',
time_created: '2014-10-02 03:49:36',
url:
'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&hrid=i_Q39aN9hwZzGDUb-IWpYw&utm_campaign=yelp_api_v3&utm_me',
user: {
id: '6tPD46XZSFllvgn2vTh51A',
image_url:
'https://s3-media3.fl.yelpcdn.com/photo/A4Ww6Ks2P9WsALqOFy9cOA/o.jpg',
name: 'Espana S.',
profile_url:
'https://www.yelp.com/user_details?userid=6tPD46XZSFllvgn2vTh51A',
},
},
],
};
axios.get.mockImplementationOnce(() => Promise.resolve(response));
axios.get.mockImplementationOnce(() => Promise.resolve(responseRev));
await expect(
Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
).resolves.toEqual(params);
});
});

Related

Why is there a validation error for submitting this formik?

My problem is that I receive a validation error on my server when trying to update my user and product collection in mongodb using formik on my front end.
I add a new product as logged in user. All of the authentication is working with JWT token.
"ValidationError: Product validation failed: title: Path title is required., description: Path description is required., price: Path price is required., location: Path location is required., condition: Path condition is required., category: Path category is required."
I've looked everywhere on stack of, and tried everything for 30+ hours. If anyone could help, I'd appreciate it. I feel bad for asking this novice question, but I've been struggling.
Here is my front end code using formik and axios :
const schema = yup.object().shape({
title: yup.string().required('Title is required'),
description: yup.string().required('Description is required'),
price: yup.number().required('Price is required').positive('Price must be a positive number'),
location: yup.string().required('Location is required'),
condition: yup.string().required('Condition is required'),
category: yup.string().required('Category is required'),
});
const addProductFormik = useFormik({
initialValues: {
title: "",
description: "",
price: "",
location: "",
condition: "",
category: "",
},
validationSchema: schema,
onSubmit: async (values) =\> {
try {
const formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('price', values.price);
formData.append('location', values.location);
formData.append('condition', values.condition);
formData.append('category', values.category);
console.log(formData.get('title'));
console.log(formData.get('price'));
const url = `http://localhost:3005/product/${user._id}/add-product`;
const config = {
headers: { Authorization: 'Bearer ' + token }
};
console.log(config);
const response = await axios.post(url, formData, config);
console.log(response);
const newProduct = response.data.product;
console.log(newProduct);
// dispatch(addProduct(newProduct));
} catch (error) {
console.log(error)
console.error(error);
}
},
});
Here is my controller function to update my mongo database :
export const createProduct = async (req, res, next) => {
try {
const id = req.params.userId;
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
console.log('user was found')
const createdProduct = new Product({
title: req.body.title,
description: req.body.description,
price: req.body.price,
location: req.body.location,
condition: req.body.condition,
category: req.body.category,
});
console.log(createdProduct);
console.log('product was created')
console.log(createdProduct._id);
try {
createdProduct.save();
user.products.push(createdProduct._id);
Product.insertMany(createdProduct);
// JWT token signing
const token = jwt.sign({ userId: user.id }, 'supersecretkey', { expiresIn: '1h' });
res.status(201).json({ product: createdProduct, token });
} catch (err) {
const error = new HttpError(
'Creating product failed, please try again.',
500
);
return next(error);
}
console.log('controller function works!');
} catch (error) {
console.error(error)
res.status(404).json({ message: error.message });
}
};
Here is my Product Schema :
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
location: {
type: String,
required: true,
},
condition: {
type: String,
required: true,
},
category: {
type: String,
required: true,
enum: ["Cars", "Electronics", "Clothing", "Furniture", "Other"],
},
seller: {
type: Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
});
const Product = mongoose.model("Product", ProductSchema);
export default Product;
Here is my User Schema :
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstName: {
type: String,
required: true,
min: 2,
max: 50,
},
lastName: {
type: String,
required: true,
min: 2,
max: 50,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
products: [
{
type: Schema.Types.ObjectId,
ref: "Product",
},
],
createdAt: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model("User", UserSchema);
export default User
Now when I submit the form, there is no error on the front end. I get a 201 response and when I console log the newProduct in the addProductFormik, this is what it says :
_id: '63f27485ed59ed8c6fdff654', createdAt: '2023-02-19T19:12:05.981Z'}
createdAt: "2023-02-19T19:12:05.981Z"
_id: "63f27485ed59ed8c6fdff654"
On the back end, i get this error : "ValidationError: Product validation failed: title: Path title is required., description: Path description is required., price: Path price is required., location: Path location is required., condition: Path condition is required., category: Path category is required."
Now if you look at the console logs made in the controller function, these are the console logs that are logged on the server,
user was found
{
_id: new ObjectId("63f27485ed59ed8c6fdff654"),
createdAt: 2023-02-19T19:12:05.981Z
}
product was created
new ObjectId("63f27485ed59ed8c6fdff654")
controller function works!
So within my controller function, it finds the user in params, the createdProduct is only shown as a new ObjectId and not with all of its fields (title, description, price, etc). Somehow, it makes it through all the try blocks and console logs the controller function works. But my products collection and user collection (user.products) is not updated and I get that validation error.
Since you're using formData, you need to pass in the Content-Type through Axios headers when posting:
headers: { "Content-Type": "multipart/form-data" },
The default type is application/xml which won't work with your data.
You'll also need to make sure your backend is configured to handle that data coming in. body-parser is commonly used for this with Express.
Here's a simple configuration:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json({ limit: '10mb' ))

how can i return an array of strings in graphQL - proper setup?

Hi I am trying to figure out why I am not returning an array of strings. I have read the docs and i must say, im stuck im a bit new to this sorry for the dumb question but can someone please help me figure this out?
I cant seem to get "flickr_images": to return an array of strings. I dont know how to proceed from there. "flicker_images" constantly return null.
I setup my graphql schema like this
`
const LaunchType = new GraphQLObjectType({
name: 'Launch',
fields: () => ({
flight_number: { type: GraphQLInt },
mission_name: { type: GraphQLString },
launch_year: { type: GraphQLString },
launch_date_local: { type: GraphQLString },
launch_success: { type: GraphQLBoolean },
details: { type: GraphQLString },
rocket: { type: RocketType },
launch_site: { type: LaunchSite },
links: { type: UrlType },
}),
});
const RocketType = new GraphQLObjectType({
name: 'Rocket',
fields: () => ({
rocket_id: { type: GraphQLString },
rocket_name: { type: GraphQLString },
rocket_type: { type: GraphQLString },
}),
});
const UrlType = new GraphQLObjectType({
name: 'Url',
fields: () => ({
mission_patch_small: { type: GraphQLString },
flickr_images: { type: new GraphQLList(GraphQLString) },
}),
});
rocket: {
type: RocketType,
args: {
id: { type: GraphQLInt },
},
resolve(parent, args) {
return axios
.get(`https://api.spacexdata.com/v3/rockets/${args.id}`)
.then((res) => res.data);
},
},
links: {
type: UrlType,
args: {
flight_number: { type: GraphQLInt },
},
resolve(parent, args) {
return axios
.get(`https://api.spacexdata.com/v3/launches/${args.flight_number}`)
.then((res) => res.data);
},
},
`
UPDATED
I'm guessing that axios.get(api.spacexdata.com/v3/rockets/${args.id}) isn't returning an array of flickr images as part of its payload. You're going to need a separate resolver under your rocket to resolve that field.

Mongoose ValidationError: Product validation failed: CountInStock: Path `CountInStock` is required

I am a beginner to React.I am working in MERN stack project and I am following this tutorial. In my case, connection to the DB was success. However, I was unable to display products in my Home screen and when I tried with this link http://localhost:5000/api/seed nodemon app get crashed and display this error.
(node:28916) [MONGODB DRIVER] Warning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2965
this.$__.validationError = new ValidationError(this);
^
ValidationError: Product validation failed: CountInStock: Path CountInStock is required.
at model.Document.invalidate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2965:32)
at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2754:17
at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1333:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: {
CountInStock: ValidatorError: Path CountInStock is required.
at validate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1330:13)
at SchemaNumber.SchemaType.doValidate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1314:7)
at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2746:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: {
validator: [Function (anonymous)],
message: 'Path CountInStock is required.',
type: 'required',
path: 'CountInStock',
value: undefined
},
kind: 'required',
path: 'CountInStock',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Product validation failed'
}
[nodemon] app crashed - waiting for file changes before starting...
Here is my Schema:
import mongoose from 'mongoose';
const productSchema = new mongoose.Schema(
{
name: { type: String, required: true, unique: true },
slug: { type: String, required: true, unique: true },
image: { type: String, required: true },
brand: { type: String, required: true },
category: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
CountInStock: { type: Number, required: true },
rating: { type: Number, required: true },
numReviews: { type: Number, required: true },
},
{
timestamps: true,
}
);
const Product = mongoose.model('Product', productSchema);
export default Product;
Here is my server.js:
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import seedRouter from './routes/seedRoutes.js';
import productRouter from './routes/ProductRoutes.js';
dotenv.config();
mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log('connected to db');
})
.catch((err) => {
console.log(err.message);
});
const app = express();
app.use('/api/seed', seedRouter);
app.use('/api/products', productRouter);
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`server at http://localhost:${port}`);
});
And Here is my seedRoutes.js file :
import express from 'express';
import Product from '../models/productModel.js';
import data from '../data.js';
const seedRouter = express.Router();
seedRouter.get('/', async (req, res) => {
await Product.remove({});
const createdProducts = await Product.insertMany(data.products);
res.send({ createdProducts });
});
export default seedRouter;
And my data.js file :
const data = {
products: [
{
name: 'Nike Soccer Football',
slug: 'nike-soccer-football',
category: 'Shoes',
image: '/images/p1.jpg',
price: 120,
countInStock: 10,
brand: 'Nike',
rating: 4.5,
numReviews: 10,
description: 'high quality pair of shoes',
},
{
name: 'Adidas Soccer Football',
slug: 'adidas-soccer-football',
category: 'Shoes',
image: '/images/p2.jpg',
price: 250,
countInStock: 0,
brand: 'Adidas',
rating: 4.0,
numReviews: 10,
description: 'high quality pair of shoes',
},
{
name: 'Nike Slim Pant',
slug: 'nike-slim-pant',
category: 'Pants',
image: '/images/p3.jpg',
price: 65,
countInStock: 5,
brand: 'Nike',
rating: 4.5,
numReviews: 14,
description: 'high quality product',
},
{
name: 'Adidas Fit Pant',
slug: 'Adidas-fit-pant',
category: 'Pants',
image: '/images/p4.jpg',
price: 25,
countInStock: 15,
brand: 'Puma',
rating: 4.5,
numReviews: 10,
description: 'high quality pair of shoes',
},
],
};
export default data;
Can I know the error that I have done here? Is it regarding the file type that I have imported in server.js file?
I think it is rather a typo. You have CountInStock in the schema definition, but countInStock in your data file. Javascript object keys are case-sensitive and therefore the case should match.

How to Test Apollo mutation with one variable set to random?

I am working on testing my Components using Appolo Mock provider. However, I have this mutation query wherein one of my variables is set to a random UUID. How could I test it? It is giving me an error of no mock response for this query since my query does not match my mock please help tnx.
Component
const [createMenuProduct, { loading }] = useMutation(CREATE_MENU_PRODUCTS);
createMenuProduct({
variables: {
menuId: menuId,
id: uuid(),
productId: selectedProduct,
},
});
test Mock
{
request: {
query: CREATE_MENU_PRODUCTS,
variables: {
menuId: menuId,
id: uuid(),
productId: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',
},
},
result: {
data: {
insertMenuProducts: {
returning: [
{
menu_id: 'b591993d-af18-4bf5-88ad-26f08691afc7',
product_id: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',
product: {
variant: {
id: '04befbe6-9635-4dde-abc2-673af13eb462',
isDeleted: false,
productVariantAddOns: [],
},
},
},
],
},
},
},
},
currenly iam encountering this error due to I cannot match my mock variable with what is expected
You could mock the returned value by uuid() to have the same as in the mock
const uuidVariable = 'mocked-uuid';
...
{
request: {
query: CREATE_MENU_PRODUCTS,
variables: {
menuId: menuId,
id: uuidVariable,
productId: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',
...
in your test
import uuid from 'uuid/v4';
jest.mock('uuid/v4');
describe('some component', () => {
it('call mutation', () => {
uuid.mockImplementation(() => uuidVariable);
// here render component and interact to fire the mutation
});
});

AssertionError [ERR_ASSERTION]: Mocks not yet satisfied: on using chaining with nock while testing Redux actions

I am trying to test an action in a React project with redux.
The test i am trying to do using Mocha,Enzyme is for a DELETE_USER action which is dispatched first on pressing a delete button and onSuccess of the action another action LOAD_ALL_USERS is dispatched which performs a get request.
Following is the code for test i tried , which gives the error as in the topic:
it('should call the /users endpoint with a user ID', (done) => {
const deleteUserResponse = {userId: 1337};
const mapActions = (actions) => ({
deleteActions: filterForAction(actions, 'DELETE_USER'),
loadAllUserActions: filterForAction(
actions,
'LOAD_ALL_USERS'
)
});
const loadAllUsersResponse =
[
{
id: 1337,
email: 'testuser9#some-company.com',
firstName: 'John',
lastName: 'Doe',
active: false
},
{
id: 1338,
email: 'adamsmith#mail.com',
firstName: 'Adam',
lastName: 'Smith',
active: true
}
];
const sampleApiSearchParams = {
locale: 'en-GB',
pageSize: 10,
sortBy: 'userId',
sortDirection: 'desc',
location: 'Zurich'
};
const sampleReactTableSearchParams = {
filtered: [
{id: 'userId', value: '1id'},
{id: 'userFirstName', value: 'fname'},
{id: 'userLastName', value: 'lname'},
{id: 'userEmail', value: 'maill'}
],
sorted: [{id: 'userId', desc: true}],
pageSize: 10
};
const scope = nock('http://localhost')
.delete('users/1337')
.reply(200, deleteUserResponse)
.get(uri=>uri.includes('users'),{...sampleApiSearchParams})
.reply(200, loadAllUsersResponse);
const store = mockStore(
{
stringResources: {
'deleteuser.confirm.title': 'User Delete Confirm',
'deleteuser.confirm.description':
'Are you sure you want to delete the user?',
'deleteuser.notification.message.success':
'is successfully deleted.'
},
userManagement: {
table: {
searchParams: sampleReactTableSearchParams
}
}
});
const actual = actions.deleteUser(1337)
store.dispatch(actual);
setTimeout(() => {
scope.done();
const {deleteActions, loadAllUsersActions} = mapActions(store.getActions());
expect(
deleteActions[1].meta['redux-pack/LIFECYCLE']
).toBe('success');
expect(deleteActions[1].payload).toEqual(
deleteUserResponse
);
//expect(loadAllUsersActions[1].payload).toEqual(loadAllUsersResponse);
done();
}, 50);
});
});
If i comment the 'scope.done()' the test passes, but http.get request is not getting called so the 'loadAllUsersActions' is undefined. How can i solve this , what is that i am doing wrong ?
Thanks in advance.

Resources