hapi + jest / how testing update user? - prisma

I have problem with one test:
test('update user', async () => {
const updatedFirstName = 'test-first-name-UPDATED'
const updatedLastName = 'test-last-name-UPDATED'
const response = await server.inject({
method: 'PUT',
url: `/users/${userId}`,
payload: {
firstName: updatedFirstName,
lastName: updatedLastName,
},
})
expect(response.statusCode).toEqual(200)
const user = JSON.parse(response.payload)
expect(user.firstName).toEqual(updatedFirstName)
expect(user.lastName).toEqual(updatedLastName)
})
I get:
expect(received).toEqual(expected) // deep equality Expected: 200 / Received: 500.
Bellow full code:
https://pastebin.com/i8JjbkeE
https://pastebin.com/cTshA0PW
What is wrong with this test?
My database is empty ofc.

Related

Express graphql mutation giving empty result after creating user

server:
const { ApolloServer, gql } = require("apollo-server-express");
const express = require("express");
const mongoose = require("mongoose");
const { userResolvers } = require("./resolvers");
const { typeDefs } = require("./typeDefs");
const startServer = async () => {
await mongoose.connect("mongodb://localhost:27017/school", {
useNewUrlParser: true,
});
const server = new ApolloServer({
typeDefs,
userResolvers,
});
await server.start();
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
};
startServer();
resolver
const User = require("./models/userModel").Users;
const userResolvers = {
Mutation: {
addUser: (parent, args) => {
let User = new User({
name: args.name,
email: args.email,
password: args.password,
otp: args.otp,
});
return User.save();
},
},
};
module.exports = { userResolvers };
typedefs
const { gql } = require("apollo-server-express");
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
password: String!
otp: Float!
}
type Mutation {
addUser(name: String!, email: String!, password: String!, otp: Int!): User
updateUser(
name: String!
email: String!
password: String!
otp: Int!
): User
deleteUser(id: ID!): User
}
`;
module.exports = { typeDefs };
here is my graphql code. Here i am trying to create user. But when i am creating a user in graphql it is sending null as response
It is not thowing any error so it is unclear for me .
Please take a look what can be the error
I have attached the screenshot also
Your local definition of User
let User = new User(...);
overwrites the global definition
const User = require("./models/userModel").Users;
This should lead to an exception
Cannot access 'User' before initialization
in the addUser function, which probably causes the null response.
Use a different name for the local definition, e.g., in lower case:
let user = new User({
name: args.name,
email: args.email,
password: args.password,
otp: args.otp,
});
return user.save();

How to send an object via fetch() to a dynamic api route in Next.js [duplicate]

This question already has answers here:
POST Request with Fetch API?
(7 answers)
Closed last year.
I am having trouble sending an object to my dynamic api route in Next. Sending a regular string works fine and I am able to update my MongoDB without issue. When sending the object though the request data just shows up as [object Object].
This is the current code snippet:
Client Side
let bookData = {
title: data[i].title,
author: data[i].author,
date: data[i].date,
isbn: data[i].isbn,
description: data[i].description,
image: data[i].image
}
fetch(`/api/db/saveBook/${bookData}`);
API Route: /pages/api/db/saveBook/[book].js
import { MongoClient } from "mongodb";
export default async function handler(req, res) {
const book = req.query;
const client = await MongoClient.connect(process.env.MONGODB_URI);
const db = client.db();
const collection = db.collection('books');
const addBook = await collection.insertOne(book);
client.close();
res.json(addBook);
}
consider 2 steps first send data through post request, then specify the content type through fetch request. see the example:
const req = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
});
So this was a case of me misunderstanding when to use Dynamic API routes within next. Below is the correct implementation of what I was trying to do, which is just a basic POST request using fetch as others mentioned here.
Client:
// Store book data to be sent to API route
let bookData = {
title: data[i].title,
author: data[i].author,
date: data[i].date,
isbn: data[i].isbn,
description: data[i].description,
image: data[i].image
}
// Send the book data to the backend API to be saved
fetch('/api/db/saveBook',
{
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(bookData),
}
);
API Route:
import { MongoClient } from "mongodb";
export default async function handler(req, res) {
const book = req.body;
const client = await MongoClient.connect(process.env.MONGODB_URI);
const db = client.db();
const collection = db.collection('books');
const addBook = await collection.insertOne(book);
client.close();
res.json(addBook);
}

Redirecting url with Puppeteer by changing url

I am trying to get change my request url and see the new url in the response
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url().includes('some-string')) {
interceptedRequest.respond({
status: 302,
headers: {
url: 'www.new.url.com'
},
})
}
interceptedRequest.continue()
});
page.on('response', response => {
console.log(response.url())
})
await page.goto('www.orginal.url.com')
// some code omitted
})();
In the interceptedRequest.respond method I'm trying to update the value of the url. Originally I was trying:
interceptedRequest.continue({url: 'www.new.url.com'})
but that way is not long supported in the current version of Puppeteer.
I was expecting to get www.new.url.com in the response, but I actually get the orignial url with www.new.url.com appended to the end.
Thanks in advance for any help.
It helped me. You need to change url to location
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url().includes('some-string')) {
interceptedRequest.respond({
status: 302,
headers: {
location: 'www.new.url.com'
},
})
}
});
page.on('response', response => {
console.log(response.url())
})
await page.goto('www.orginal.url.com')
// some code omitted
})();

axios request not going through to backend

I'm struggling getting this axios call to work. It's in a password reset feature, and it calls an axios request that sends through to the back end, but it's just coming up with an error instead of executing the code in the router route.
I call the request in this block here.
front end side:
async componentDidMount() {
const {
match: {
params: { token },
},
} = this.props;
try {
const response = await axios.get('http://localhost:5000/api/users/reset', {
params: {
resetPasswordToken: token,
},
});
console.log(response)
if (response.data.message === 'password reset link a-ok') {
this.setState({
username: response.data.username,
updated: false,
isLoading: false,
error: false,
});
}
} catch (error) {
console.log(error.response.data);
this.setState({
updated: false,
isLoading: false,
error: true,
});
}
}
It's getting the proper token and everything, but the http://localhost:5000/api/users/reset should be pointing to the /reset route in the code below, and it's never reached.
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
const nodemailer = require('nodemailer');
const crypto = require('crypto');
require('dotenv').config();
const User = require("../../models/User");
router.route('/reset').get((req, res, next) => {
User.find({
where: {resetPasswordToken: req.query.resetPasswordToken,
resetPasswordExpires: {
$gt: Date.now(),
},
},
}).then(user => {
if(user == null) {
console.log('password reset link is invalid or has expired');
res.json('password reset link is invalid or has expired');
}else{
res.status(200).send({
username: user.username,
message: 'password reset link a-ok',
});
}
});
});
module.exports = router;
Actually #TamasSzoke you led me to answer my own question so I thank you! I had another route that was just /:id and that's what it was trying to validate there.
Just have to change that one up and it'll be all good.
thank you!!!

How to send a SOAP request with Jest and Supertest?

What I need is to send a SOAP request, which is a XML file.
How I can send the content which is a XML file as a post request?
Here is an example:
app.js:
const express = require('express');
const app = express();
const xmlparser = require('express-xml-bodyparser');
app.use(xmlparser());
app.post('/', (req, res) => {
res.json(req.body);
});
module.exports = app;
app.test.js:
const app = require('./app');
const request = require('supertest');
describe('57353993', () => {
// read from XML file
var itemsXML = '<list><item>item1</item><item>item2</item><item>item3</item></list>';
var itemList = {
list: {
item: ['item1', 'item2', 'item3'],
},
};
it('should pass', async () => {
const res = await request(app)
.post('/')
.set('Content-Type', 'application/xml')
.send(itemsXML);
expect(res.status).toBe(200);
expect(res.body).toEqual(itemList);
});
});
Test result:
PASS src/stackoverflow/57353993/app.test.js (9.465s)
57353993
✓ should pass (56ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.598s, estimated 11s
You should be able to do this:
const xml = "<note><to>Hello</to><from>World</from></note>"
const res = await request(app)
.post('/')
.set('Content-Type', 'application/xml')
.send(xml);