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.