I'm building a react native app that connects to a forum with the user account and gets some data from there. I'm trying to make fetch use cookies on my tests with jest, but looks like is not working.
I use isomorphic-fetch to have fetch available on my test environment.
My code is like this:
jest.setup.js:
import "isomorphic-fetch"
main.js:
var iconv = require('iconv-lite');
var Entities = require("html-entities").AllHtmlEntities;
const entities = new Entities();
function _textToUTF8(t) {
return entities.decode(iconv.decode(t, "windows-1252"));
}
function _generateFormData(d) {
var output = [];
for (var i in d) {
output.push(i + "=" + d[i]);
}
return output.join("&");
}
function _isLoggedIn(t) {
return t.indexOf("logout") >= 0 ? true : false;
}
function _getWebpage(url, r) {
return new Promise((resolve, reject) => {
fetch(url, r).then((response) => {
response.buffer().then((buffer) => {
var t = _textToUTF8(buffer);
console.log("Is logged in", url, _isLoggedIn(t));
resolve(t);
})
})
})
}
function login(username, password, cookieJar) {
var d = _generateFormData({
"username": username,
"password": password,
});
var h = {
"Content-Type": "application/x-www-form-urlencoded",
};
var r = {
method: "POST",
body: d,
headers: h,
credentials: "include",
};
var u = BASE_URL + "login.php";
return _getWebpage(u, r);
}
describe("TEST", () => {
it("Keeps session cookies", (done) => {
login("user", "password").then(() => {
_getWebpage(BASE_URL + "forumpage.php", {method: "GET", credentials: "include"}).then((r) => {
expect(_isLoggedIn(r)).toBe(true);
done();
})
})
})
})
// Is logged in https://www.website.com/login.php true
// Is logged in https://www.website.com/forumpage.php false
Looks like is not sending any cookies for some reason, it login as expected on the first request, but then the second one is not logged in. How can I make it work?
By the way, if I change credentials: include for credentials: same-origin, it doesn't work either.