Reputation: 508
EDIT: The variable username
becomes undefined
for some reason. I tried passing other variables too, but none of them appear as they should with console.log()
.
I have a jest file ("index.test.js") for testing my API:
'use strict';
const request = require('supertest');
const app = require('./index');
describe('Test login', () => {
test('POST /login', () => {
return request(app)
.post('/login')
.send({username: 'preset1'}) //suggestion by @acincognito
.expect(301)
});
});
and a corresponding POST route in my nodejs file ("index.js"):
...
function contains(arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if(arr[i][key] === val) {
return true
};
}
return false;
}
app.post("/login", async (req, res) => {
try {
var username = req.body.username;
const data = await readFile("results.json");
var json = JSON.parse(data);
if (contains(json, "name", username) === true){
...
return res.redirect(301,"/");
} else {
return res.redirect(401,"/");
}
} catch (error) {
return res.redirect("/");
}
});
JSON file ("results.json") has the following format:
[
{"name":"preset1","otherstuff":[]},
...
{"name":"preset5","otherstuff":[]}
]
I am getting the error message :
expected 301 "Moved Permanently", got 401 "Unauthorized"
NOTE: When I run the code manually on a local server, everything works as it should which seems to contradict the output of the test.
Upvotes: 0
Views: 2597
Reputation: 508
I needed to encode a Javascript Object into a string.
function serialize(obj){
return Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
}
// Code from : https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object
Instead of:
.send({username: 'preset1'})
Replace with:
.send(serialize({username: 'preset1'}))
Edit: This did not work for all parameters.
Upvotes: 0
Reputation: 1743
Add a console.log(json)
to your app.post
function to see what gets parsed.
After looking at the docs for supertest
: apparently .set('username','preset1')
is for setting headers in your request, but according to your app.post
username
is inside the request's body, therefore try .send({username: 'preset1'})
.
Upvotes: 1