@wordpress/e2e-test-utils
Version:
End-To-End (E2E) test utils for WordPress.
84 lines (83 loc) • 2.36 kB
JavaScript
import fetch from "node-fetch";
import FormData from "form-data";
import apiFetch from "@wordpress/api-fetch";
import { WP_BASE_URL, WP_USERNAME, WP_PASSWORD } from "./shared/config";
import { createURL } from "./create-url";
global.window = global.window || {};
global.window.fetch = fetch;
const setAPIRootURL = (async () => {
const res = await fetch(WP_BASE_URL, { method: "HEAD" });
const links = res.headers.get("link");
const restLink = links.match(/<([^>]+)>; rel="https:\/\/api\.w\.org\/"/);
if (!restLink) {
throw new Error(`Failed to discover REST API endpoint.
Link header: ${links}`);
}
const [, rootURL] = restLink;
apiFetch.use(apiFetch.createRootURLMiddleware(rootURL));
})();
async function login(retries = 3) {
const formData = new FormData();
formData.append("log", WP_USERNAME);
formData.append("pwd", WP_PASSWORD);
const loginResponse = await fetch(createURL("wp-login.php"), {
method: "POST",
headers: formData.getHeaders(),
body: formData,
redirect: "manual"
});
const cookies = loginResponse.headers.get("set-cookie");
const cookie = cookies.split(",").map((setCookie) => setCookie.split(";")[0]).join(";");
apiFetch.nonceEndpoint = createURL(
"wp-admin/admin-ajax.php",
"action=rest-nonce"
);
const response = await fetch(apiFetch.nonceEndpoint, {
headers: { cookie }
});
if (response.status === 200) {
return {
response,
cookie
};
}
if (retries > 0) {
return login(retries - 1);
}
throw new Error(
`Fetch api call failed for ${apiFetch.nonceEndpoint}: ${response.status}`
);
}
const setNonce = (async () => {
const loginRequest = await login();
const nonce = await loginRequest.response.text();
apiFetch.use(apiFetch.createNonceMiddleware(nonce));
apiFetch.use(function setCookieMiddleware(request, next) {
return next({
...request,
headers: {
...request.headers,
cookie: loginRequest.cookie
}
});
});
})();
async function rest(options = {}) {
await Promise.all([setAPIRootURL, setNonce]);
return await apiFetch(options);
}
async function batch(requests) {
return await rest({
method: "POST",
path: "/batch/v1",
data: {
requests,
validation: "require-all-validate"
}
});
}
export {
batch,
rest
};
//# sourceMappingURL=rest-api.js.map