我正在构建一个反应原生应用程序,该应用程序使用用户帐户连接到论坛并从那里获取一些数据。我正在尝试fetch
在我的测试中使用 cookie jest
,但看起来不起作用。
我isomorphic-fetch
曾经fetch
在我的测试环境中可用。
我的代码是这样的:
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
看起来由于某种原因没有发送任何 cookie,它在第一个请求时按预期登录,但第二个请求没有登录。我怎样才能让它工作?
顺便说一句,如果我更改credentials: include
为credentials: same-origin
,它也不起作用。