repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/fetchers/top-languages.js | src/fetchers/top-languages.js | // @ts-check
import { retryer } from "../common/retryer.js";
import { logger } from "../common/log.js";
import { excludeRepositories } from "../common/envs.js";
import { CustomError, MissingParamError } from "../common/error.js";
import { wrapTextMultiline } from "../common/fmt.js";
import { request } from "../common/http.js";
/**
* Top languages fetcher object.
*
* @param {any} variables Fetcher variables.
* @param {string} token GitHub token.
* @returns {Promise<import("axios").AxiosResponse>} Languages fetcher response.
*/
const fetcher = (variables, token) => {
return request(
{
query: `
query userInfo($login: String!) {
user(login: $login) {
# fetch only owner repos & not forks
repositories(ownerAffiliations: OWNER, isFork: false, first: 100) {
nodes {
name
languages(first: 10, orderBy: {field: SIZE, direction: DESC}) {
edges {
size
node {
color
name
}
}
}
}
}
}
}
`,
variables,
},
{
Authorization: `token ${token}`,
},
);
};
/**
* @typedef {import("./types").TopLangData} TopLangData Top languages data.
*/
/**
* Fetch top languages for a given username.
*
* @param {string} username GitHub username.
* @param {string[]} exclude_repo List of repositories to exclude.
* @param {number} size_weight Weightage to be given to size.
* @param {number} count_weight Weightage to be given to count.
* @returns {Promise<TopLangData>} Top languages data.
*/
const fetchTopLanguages = async (
username,
exclude_repo = [],
size_weight = 1,
count_weight = 0,
) => {
if (!username) {
throw new MissingParamError(["username"]);
}
const res = await retryer(fetcher, { login: username });
if (res.data.errors) {
logger.error(res.data.errors);
if (res.data.errors[0].type === "NOT_FOUND") {
throw new CustomError(
res.data.errors[0].message || "Could not fetch user.",
CustomError.USER_NOT_FOUND,
);
}
if (res.data.errors[0].message) {
throw new CustomError(
wrapTextMultiline(res.data.errors[0].message, 90, 1)[0],
res.statusText,
);
}
throw new CustomError(
"Something went wrong while trying to retrieve the language data using the GraphQL API.",
CustomError.GRAPHQL_ERROR,
);
}
let repoNodes = res.data.data.user.repositories.nodes;
/** @type {Record<string, boolean>} */
let repoToHide = {};
const allExcludedRepos = [...exclude_repo, ...excludeRepositories];
// populate repoToHide map for quick lookup
// while filtering out
if (allExcludedRepos) {
allExcludedRepos.forEach((repoName) => {
repoToHide[repoName] = true;
});
}
// filter out repositories to be hidden
repoNodes = repoNodes
.sort((a, b) => b.size - a.size)
.filter((name) => !repoToHide[name.name]);
let repoCount = 0;
repoNodes = repoNodes
.filter((node) => node.languages.edges.length > 0)
// flatten the list of language nodes
.reduce((acc, curr) => curr.languages.edges.concat(acc), [])
.reduce((acc, prev) => {
// get the size of the language (bytes)
let langSize = prev.size;
// if we already have the language in the accumulator
// & the current language name is same as previous name
// add the size to the language size and increase repoCount.
if (acc[prev.node.name] && prev.node.name === acc[prev.node.name].name) {
langSize = prev.size + acc[prev.node.name].size;
repoCount += 1;
} else {
// reset repoCount to 1
// language must exist in at least one repo to be detected
repoCount = 1;
}
return {
...acc,
[prev.node.name]: {
name: prev.node.name,
color: prev.node.color,
size: langSize,
count: repoCount,
},
};
}, {});
Object.keys(repoNodes).forEach((name) => {
// comparison index calculation
repoNodes[name].size =
Math.pow(repoNodes[name].size, size_weight) *
Math.pow(repoNodes[name].count, count_weight);
});
const topLangs = Object.keys(repoNodes)
.sort((a, b) => repoNodes[b].size - repoNodes[a].size)
.reduce((result, key) => {
result[key] = repoNodes[key];
return result;
}, {});
return topLangs;
};
export { fetchTopLanguages };
export default fetchTopLanguages;
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/src/fetchers/stats.js | src/fetchers/stats.js | // @ts-check
import axios from "axios";
import * as dotenv from "dotenv";
import githubUsernameRegex from "github-username-regex";
import { calculateRank } from "../calculateRank.js";
import { retryer } from "../common/retryer.js";
import { logger } from "../common/log.js";
import { excludeRepositories } from "../common/envs.js";
import { CustomError, MissingParamError } from "../common/error.js";
import { wrapTextMultiline } from "../common/fmt.js";
import { request } from "../common/http.js";
dotenv.config();
// GraphQL queries.
const GRAPHQL_REPOS_FIELD = `
repositories(first: 100, ownerAffiliations: OWNER, orderBy: {direction: DESC, field: STARGAZERS}, after: $after) {
totalCount
nodes {
name
stargazers {
totalCount
}
}
pageInfo {
hasNextPage
endCursor
}
}
`;
const GRAPHQL_REPOS_QUERY = `
query userInfo($login: String!, $after: String) {
user(login: $login) {
${GRAPHQL_REPOS_FIELD}
}
}
`;
const GRAPHQL_STATS_QUERY = `
query userInfo($login: String!, $after: String, $includeMergedPullRequests: Boolean!, $includeDiscussions: Boolean!, $includeDiscussionsAnswers: Boolean!, $startTime: DateTime = null) {
user(login: $login) {
name
login
commits: contributionsCollection (from: $startTime) {
totalCommitContributions,
}
reviews: contributionsCollection {
totalPullRequestReviewContributions
}
repositoriesContributedTo(first: 1, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
totalCount
}
pullRequests(first: 1) {
totalCount
}
mergedPullRequests: pullRequests(states: MERGED) @include(if: $includeMergedPullRequests) {
totalCount
}
openIssues: issues(states: OPEN) {
totalCount
}
closedIssues: issues(states: CLOSED) {
totalCount
}
followers {
totalCount
}
repositoryDiscussions @include(if: $includeDiscussions) {
totalCount
}
repositoryDiscussionComments(onlyAnswers: true) @include(if: $includeDiscussionsAnswers) {
totalCount
}
${GRAPHQL_REPOS_FIELD}
}
}
`;
/**
* Stats fetcher object.
*
* @param {object & { after: string | null }} variables Fetcher variables.
* @param {string} token GitHub token.
* @returns {Promise<import('axios').AxiosResponse>} Axios response.
*/
const fetcher = (variables, token) => {
const query = variables.after ? GRAPHQL_REPOS_QUERY : GRAPHQL_STATS_QUERY;
return request(
{
query,
variables,
},
{
Authorization: `bearer ${token}`,
},
);
};
/**
* Fetch stats information for a given username.
*
* @param {object} variables Fetcher variables.
* @param {string} variables.username GitHub username.
* @param {boolean} variables.includeMergedPullRequests Include merged pull requests.
* @param {boolean} variables.includeDiscussions Include discussions.
* @param {boolean} variables.includeDiscussionsAnswers Include discussions answers.
* @param {string|undefined} variables.startTime Time to start the count of total commits.
* @returns {Promise<import('axios').AxiosResponse>} Axios response.
*
* @description This function supports multi-page fetching if the 'FETCH_MULTI_PAGE_STARS' environment variable is set to true.
*/
const statsFetcher = async ({
username,
includeMergedPullRequests,
includeDiscussions,
includeDiscussionsAnswers,
startTime,
}) => {
let stats;
let hasNextPage = true;
let endCursor = null;
while (hasNextPage) {
const variables = {
login: username,
first: 100,
after: endCursor,
includeMergedPullRequests,
includeDiscussions,
includeDiscussionsAnswers,
startTime,
};
let res = await retryer(fetcher, variables);
if (res.data.errors) {
return res;
}
// Store stats data.
const repoNodes = res.data.data.user.repositories.nodes;
if (stats) {
stats.data.data.user.repositories.nodes.push(...repoNodes);
} else {
stats = res;
}
// Disable multi page fetching on public Vercel instance due to rate limits.
const repoNodesWithStars = repoNodes.filter(
(node) => node.stargazers.totalCount !== 0,
);
hasNextPage =
process.env.FETCH_MULTI_PAGE_STARS === "true" &&
repoNodes.length === repoNodesWithStars.length &&
res.data.data.user.repositories.pageInfo.hasNextPage;
endCursor = res.data.data.user.repositories.pageInfo.endCursor;
}
return stats;
};
/**
* Fetch total commits using the REST API.
*
* @param {object} variables Fetcher variables.
* @param {string} token GitHub token.
* @returns {Promise<import('axios').AxiosResponse>} Axios response.
*
* @see https://developer.github.com/v3/search/#search-commits
*/
const fetchTotalCommits = (variables, token) => {
return axios({
method: "get",
url: `https://api.github.com/search/commits?q=author:${variables.login}`,
headers: {
"Content-Type": "application/json",
Accept: "application/vnd.github.cloak-preview",
Authorization: `token ${token}`,
},
});
};
/**
* Fetch all the commits for all the repositories of a given username.
*
* @param {string} username GitHub username.
* @returns {Promise<number>} Total commits.
*
* @description Done like this because the GitHub API does not provide a way to fetch all the commits. See
* #92#issuecomment-661026467 and #211 for more information.
*/
const totalCommitsFetcher = async (username) => {
if (!githubUsernameRegex.test(username)) {
logger.log("Invalid username provided.");
throw new Error("Invalid username provided.");
}
let res;
try {
res = await retryer(fetchTotalCommits, { login: username });
} catch (err) {
logger.log(err);
throw new Error(err);
}
const totalCount = res.data.total_count;
if (!totalCount || isNaN(totalCount)) {
throw new CustomError(
"Could not fetch total commits.",
CustomError.GITHUB_REST_API_ERROR,
);
}
return totalCount;
};
/**
* Fetch stats for a given username.
*
* @param {string} username GitHub username.
* @param {boolean} include_all_commits Include all commits.
* @param {string[]} exclude_repo Repositories to exclude.
* @param {boolean} include_merged_pull_requests Include merged pull requests.
* @param {boolean} include_discussions Include discussions.
* @param {boolean} include_discussions_answers Include discussions answers.
* @param {number|undefined} commits_year Year to count total commits
* @returns {Promise<import("./types").StatsData>} Stats data.
*/
const fetchStats = async (
username,
include_all_commits = false,
exclude_repo = [],
include_merged_pull_requests = false,
include_discussions = false,
include_discussions_answers = false,
commits_year,
) => {
if (!username) {
throw new MissingParamError(["username"]);
}
const stats = {
name: "",
totalPRs: 0,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 0,
totalCommits: 0,
totalIssues: 0,
totalStars: 0,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
contributedTo: 0,
rank: { level: "C", percentile: 100 },
};
let res = await statsFetcher({
username,
includeMergedPullRequests: include_merged_pull_requests,
includeDiscussions: include_discussions,
includeDiscussionsAnswers: include_discussions_answers,
startTime: commits_year ? `${commits_year}-01-01T00:00:00Z` : undefined,
});
// Catch GraphQL errors.
if (res.data.errors) {
logger.error(res.data.errors);
if (res.data.errors[0].type === "NOT_FOUND") {
throw new CustomError(
res.data.errors[0].message || "Could not fetch user.",
CustomError.USER_NOT_FOUND,
);
}
if (res.data.errors[0].message) {
throw new CustomError(
wrapTextMultiline(res.data.errors[0].message, 90, 1)[0],
res.statusText,
);
}
throw new CustomError(
"Something went wrong while trying to retrieve the stats data using the GraphQL API.",
CustomError.GRAPHQL_ERROR,
);
}
const user = res.data.data.user;
stats.name = user.name || user.login;
// if include_all_commits, fetch all commits using the REST API.
if (include_all_commits) {
stats.totalCommits = await totalCommitsFetcher(username);
} else {
stats.totalCommits = user.commits.totalCommitContributions;
}
stats.totalPRs = user.pullRequests.totalCount;
if (include_merged_pull_requests) {
stats.totalPRsMerged = user.mergedPullRequests.totalCount;
stats.mergedPRsPercentage =
(user.mergedPullRequests.totalCount / user.pullRequests.totalCount) *
100 || 0;
}
stats.totalReviews = user.reviews.totalPullRequestReviewContributions;
stats.totalIssues = user.openIssues.totalCount + user.closedIssues.totalCount;
if (include_discussions) {
stats.totalDiscussionsStarted = user.repositoryDiscussions.totalCount;
}
if (include_discussions_answers) {
stats.totalDiscussionsAnswered =
user.repositoryDiscussionComments.totalCount;
}
stats.contributedTo = user.repositoriesContributedTo.totalCount;
// Retrieve stars while filtering out repositories to be hidden.
const allExcludedRepos = [...exclude_repo, ...excludeRepositories];
let repoToHide = new Set(allExcludedRepos);
stats.totalStars = user.repositories.nodes
.filter((data) => {
return !repoToHide.has(data.name);
})
.reduce((prev, curr) => {
return prev + curr.stargazers.totalCount;
}, 0);
stats.rank = calculateRank({
all_commits: include_all_commits,
commits: stats.totalCommits,
prs: stats.totalPRs,
reviews: stats.totalReviews,
issues: stats.totalIssues,
repos: user.repositories.totalCount,
stars: stats.totalStars,
followers: user.followers.totalCount,
});
return stats;
};
export { fetchStats };
export default fetchStats;
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/renderTopLanguagesCard.test.js | tests/renderTopLanguagesCard.test.js | import { describe, expect, it } from "@jest/globals";
import { queryAllByTestId, queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom";
import { cssToObject } from "@uppercod/css-to-object";
import {
MIN_CARD_WIDTH,
calculateCompactLayoutHeight,
calculateDonutLayoutHeight,
calculateDonutVerticalLayoutHeight,
calculateNormalLayoutHeight,
calculatePieLayoutHeight,
cartesianToPolar,
degreesToRadians,
donutCenterTranslation,
getCircleLength,
getDefaultLanguagesCountByLayout,
getLongestLang,
polarToCartesian,
radiansToDegrees,
renderTopLanguages,
trimTopLanguages,
} from "../src/cards/top-languages.js";
import { themes } from "../themes/index.js";
const langs = {
HTML: {
color: "#0f0",
name: "HTML",
size: 200,
},
javascript: {
color: "#0ff",
name: "javascript",
size: 200,
},
css: {
color: "#ff0",
name: "css",
size: 100,
},
};
/**
* Retrieve number array from SVG path definition string.
*
* @param {string} d SVG path definition string.
* @returns {number[]} Resulting numbers array.
*/
const getNumbersFromSvgPathDefinitionAttribute = (d) => {
return d
.split(" ")
.filter((x) => !isNaN(x))
.map((x) => parseFloat(x));
};
/**
* Retrieve the language percentage from the donut chart SVG.
*
* @param {string} d The SVG path element.
* @param {number} centerX The center X coordinate of the donut chart.
* @param {number} centerY The center Y coordinate of the donut chart.
* @returns {number} The percentage of the language.
*/
const langPercentFromDonutLayoutSvg = (d, centerX, centerY) => {
const dTmp = getNumbersFromSvgPathDefinitionAttribute(d);
const endAngle =
cartesianToPolar(centerX, centerY, dTmp[0], dTmp[1]).angleInDegrees + 90;
let startAngle =
cartesianToPolar(centerX, centerY, dTmp[7], dTmp[8]).angleInDegrees + 90;
if (startAngle > endAngle) {
startAngle -= 360;
}
return (endAngle - startAngle) / 3.6;
};
/**
* Calculate language percentage for donut vertical chart SVG.
*
* @param {number} partLength Length of current chart part..
* @param {number} totalCircleLength Total length of circle.
* @returns {number} Chart part percentage.
*/
const langPercentFromDonutVerticalLayoutSvg = (
partLength,
totalCircleLength,
) => {
return (partLength / totalCircleLength) * 100;
};
/**
* Retrieve the language percentage from the pie chart SVG.
*
* @param {string} d The SVG path element.
* @param {number} centerX The center X coordinate of the pie chart.
* @param {number} centerY The center Y coordinate of the pie chart.
* @returns {number} The percentage of the language.
*/
const langPercentFromPieLayoutSvg = (d, centerX, centerY) => {
const dTmp = getNumbersFromSvgPathDefinitionAttribute(d);
const startAngle = cartesianToPolar(
centerX,
centerY,
dTmp[2],
dTmp[3],
).angleInDegrees;
let endAngle = cartesianToPolar(
centerX,
centerY,
dTmp[9],
dTmp[10],
).angleInDegrees;
return ((endAngle - startAngle) / 360) * 100;
};
describe("Test renderTopLanguages helper functions", () => {
it("getLongestLang", () => {
const langArray = Object.values(langs);
expect(getLongestLang(langArray)).toBe(langs.javascript);
});
it("degreesToRadians", () => {
expect(degreesToRadians(0)).toBe(0);
expect(degreesToRadians(90)).toBe(Math.PI / 2);
expect(degreesToRadians(180)).toBe(Math.PI);
expect(degreesToRadians(270)).toBe((3 * Math.PI) / 2);
expect(degreesToRadians(360)).toBe(2 * Math.PI);
});
it("radiansToDegrees", () => {
expect(radiansToDegrees(0)).toBe(0);
expect(radiansToDegrees(Math.PI / 2)).toBe(90);
expect(radiansToDegrees(Math.PI)).toBe(180);
expect(radiansToDegrees((3 * Math.PI) / 2)).toBe(270);
expect(radiansToDegrees(2 * Math.PI)).toBe(360);
});
it("polarToCartesian", () => {
expect(polarToCartesian(100, 100, 60, 0)).toStrictEqual({ x: 160, y: 100 });
expect(polarToCartesian(100, 100, 60, 45)).toStrictEqual({
x: 142.42640687119285,
y: 142.42640687119285,
});
expect(polarToCartesian(100, 100, 60, 90)).toStrictEqual({
x: 100,
y: 160,
});
expect(polarToCartesian(100, 100, 60, 135)).toStrictEqual({
x: 57.573593128807154,
y: 142.42640687119285,
});
expect(polarToCartesian(100, 100, 60, 180)).toStrictEqual({
x: 40,
y: 100.00000000000001,
});
expect(polarToCartesian(100, 100, 60, 225)).toStrictEqual({
x: 57.57359312880714,
y: 57.573593128807154,
});
expect(polarToCartesian(100, 100, 60, 270)).toStrictEqual({
x: 99.99999999999999,
y: 40,
});
expect(polarToCartesian(100, 100, 60, 315)).toStrictEqual({
x: 142.42640687119285,
y: 57.57359312880714,
});
expect(polarToCartesian(100, 100, 60, 360)).toStrictEqual({
x: 160,
y: 99.99999999999999,
});
});
it("cartesianToPolar", () => {
expect(cartesianToPolar(100, 100, 160, 100)).toStrictEqual({
radius: 60,
angleInDegrees: 0,
});
expect(
cartesianToPolar(100, 100, 142.42640687119285, 142.42640687119285),
).toStrictEqual({ radius: 60.00000000000001, angleInDegrees: 45 });
expect(cartesianToPolar(100, 100, 100, 160)).toStrictEqual({
radius: 60,
angleInDegrees: 90,
});
expect(
cartesianToPolar(100, 100, 57.573593128807154, 142.42640687119285),
).toStrictEqual({ radius: 60, angleInDegrees: 135 });
expect(cartesianToPolar(100, 100, 40, 100.00000000000001)).toStrictEqual({
radius: 60,
angleInDegrees: 180,
});
expect(
cartesianToPolar(100, 100, 57.57359312880714, 57.573593128807154),
).toStrictEqual({ radius: 60, angleInDegrees: 225 });
expect(cartesianToPolar(100, 100, 99.99999999999999, 40)).toStrictEqual({
radius: 60,
angleInDegrees: 270,
});
expect(
cartesianToPolar(100, 100, 142.42640687119285, 57.57359312880714),
).toStrictEqual({ radius: 60.00000000000001, angleInDegrees: 315 });
expect(cartesianToPolar(100, 100, 160, 99.99999999999999)).toStrictEqual({
radius: 60,
angleInDegrees: 360,
});
});
it("calculateCompactLayoutHeight", () => {
expect(calculateCompactLayoutHeight(0)).toBe(90);
expect(calculateCompactLayoutHeight(1)).toBe(115);
expect(calculateCompactLayoutHeight(2)).toBe(115);
expect(calculateCompactLayoutHeight(3)).toBe(140);
expect(calculateCompactLayoutHeight(4)).toBe(140);
expect(calculateCompactLayoutHeight(5)).toBe(165);
expect(calculateCompactLayoutHeight(6)).toBe(165);
expect(calculateCompactLayoutHeight(7)).toBe(190);
expect(calculateCompactLayoutHeight(8)).toBe(190);
expect(calculateCompactLayoutHeight(9)).toBe(215);
expect(calculateCompactLayoutHeight(10)).toBe(215);
});
it("calculateNormalLayoutHeight", () => {
expect(calculateNormalLayoutHeight(0)).toBe(85);
expect(calculateNormalLayoutHeight(1)).toBe(125);
expect(calculateNormalLayoutHeight(2)).toBe(165);
expect(calculateNormalLayoutHeight(3)).toBe(205);
expect(calculateNormalLayoutHeight(4)).toBe(245);
expect(calculateNormalLayoutHeight(5)).toBe(285);
expect(calculateNormalLayoutHeight(6)).toBe(325);
expect(calculateNormalLayoutHeight(7)).toBe(365);
expect(calculateNormalLayoutHeight(8)).toBe(405);
expect(calculateNormalLayoutHeight(9)).toBe(445);
expect(calculateNormalLayoutHeight(10)).toBe(485);
});
it("calculateDonutLayoutHeight", () => {
expect(calculateDonutLayoutHeight(0)).toBe(215);
expect(calculateDonutLayoutHeight(1)).toBe(215);
expect(calculateDonutLayoutHeight(2)).toBe(215);
expect(calculateDonutLayoutHeight(3)).toBe(215);
expect(calculateDonutLayoutHeight(4)).toBe(215);
expect(calculateDonutLayoutHeight(5)).toBe(215);
expect(calculateDonutLayoutHeight(6)).toBe(247);
expect(calculateDonutLayoutHeight(7)).toBe(279);
expect(calculateDonutLayoutHeight(8)).toBe(311);
expect(calculateDonutLayoutHeight(9)).toBe(343);
expect(calculateDonutLayoutHeight(10)).toBe(375);
});
it("calculateDonutVerticalLayoutHeight", () => {
expect(calculateDonutVerticalLayoutHeight(0)).toBe(300);
expect(calculateDonutVerticalLayoutHeight(1)).toBe(325);
expect(calculateDonutVerticalLayoutHeight(2)).toBe(325);
expect(calculateDonutVerticalLayoutHeight(3)).toBe(350);
expect(calculateDonutVerticalLayoutHeight(4)).toBe(350);
expect(calculateDonutVerticalLayoutHeight(5)).toBe(375);
expect(calculateDonutVerticalLayoutHeight(6)).toBe(375);
expect(calculateDonutVerticalLayoutHeight(7)).toBe(400);
expect(calculateDonutVerticalLayoutHeight(8)).toBe(400);
expect(calculateDonutVerticalLayoutHeight(9)).toBe(425);
expect(calculateDonutVerticalLayoutHeight(10)).toBe(425);
});
it("calculatePieLayoutHeight", () => {
expect(calculatePieLayoutHeight(0)).toBe(300);
expect(calculatePieLayoutHeight(1)).toBe(325);
expect(calculatePieLayoutHeight(2)).toBe(325);
expect(calculatePieLayoutHeight(3)).toBe(350);
expect(calculatePieLayoutHeight(4)).toBe(350);
expect(calculatePieLayoutHeight(5)).toBe(375);
expect(calculatePieLayoutHeight(6)).toBe(375);
expect(calculatePieLayoutHeight(7)).toBe(400);
expect(calculatePieLayoutHeight(8)).toBe(400);
expect(calculatePieLayoutHeight(9)).toBe(425);
expect(calculatePieLayoutHeight(10)).toBe(425);
});
it("donutCenterTranslation", () => {
expect(donutCenterTranslation(0)).toBe(-45);
expect(donutCenterTranslation(1)).toBe(-45);
expect(donutCenterTranslation(2)).toBe(-45);
expect(donutCenterTranslation(3)).toBe(-45);
expect(donutCenterTranslation(4)).toBe(-45);
expect(donutCenterTranslation(5)).toBe(-45);
expect(donutCenterTranslation(6)).toBe(-29);
expect(donutCenterTranslation(7)).toBe(-13);
expect(donutCenterTranslation(8)).toBe(3);
expect(donutCenterTranslation(9)).toBe(19);
expect(donutCenterTranslation(10)).toBe(35);
});
it("getCircleLength", () => {
expect(getCircleLength(20)).toBeCloseTo(125.663);
expect(getCircleLength(30)).toBeCloseTo(188.495);
expect(getCircleLength(40)).toBeCloseTo(251.327);
expect(getCircleLength(50)).toBeCloseTo(314.159);
expect(getCircleLength(60)).toBeCloseTo(376.991);
expect(getCircleLength(70)).toBeCloseTo(439.822);
expect(getCircleLength(80)).toBeCloseTo(502.654);
expect(getCircleLength(90)).toBeCloseTo(565.486);
expect(getCircleLength(100)).toBeCloseTo(628.318);
});
it("trimTopLanguages", () => {
expect(trimTopLanguages([])).toStrictEqual({
langs: [],
totalLanguageSize: 0,
});
expect(trimTopLanguages([langs.javascript])).toStrictEqual({
langs: [langs.javascript],
totalLanguageSize: 200,
});
expect(trimTopLanguages([langs.javascript, langs.HTML], 5)).toStrictEqual({
langs: [langs.javascript, langs.HTML],
totalLanguageSize: 400,
});
expect(trimTopLanguages(langs, 5)).toStrictEqual({
langs: Object.values(langs),
totalLanguageSize: 500,
});
expect(trimTopLanguages(langs, 2)).toStrictEqual({
langs: Object.values(langs).slice(0, 2),
totalLanguageSize: 400,
});
expect(trimTopLanguages(langs, 5, ["javascript"])).toStrictEqual({
langs: [langs.HTML, langs.css],
totalLanguageSize: 300,
});
});
it("getDefaultLanguagesCountByLayout", () => {
expect(
getDefaultLanguagesCountByLayout({ layout: "normal" }),
).toStrictEqual(5);
expect(getDefaultLanguagesCountByLayout({})).toStrictEqual(5);
expect(
getDefaultLanguagesCountByLayout({ layout: "compact" }),
).toStrictEqual(6);
expect(
getDefaultLanguagesCountByLayout({ hide_progress: true }),
).toStrictEqual(6);
expect(getDefaultLanguagesCountByLayout({ layout: "donut" })).toStrictEqual(
5,
);
expect(
getDefaultLanguagesCountByLayout({ layout: "donut-vertical" }),
).toStrictEqual(6);
expect(getDefaultLanguagesCountByLayout({ layout: "pie" })).toStrictEqual(
6,
);
});
});
describe("Test renderTopLanguages", () => {
it("should render correctly", () => {
document.body.innerHTML = renderTopLanguages(langs);
expect(queryByTestId(document.body, "header")).toHaveTextContent(
"Most Used Languages",
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript",
);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css",
);
expect(queryAllByTestId(document.body, "lang-progress")[0]).toHaveAttribute(
"width",
"40%",
);
expect(queryAllByTestId(document.body, "lang-progress")[1]).toHaveAttribute(
"width",
"40%",
);
expect(queryAllByTestId(document.body, "lang-progress")[2]).toHaveAttribute(
"width",
"20%",
);
});
it("should hide languages when hide is passed", () => {
document.body.innerHTML = renderTopLanguages(langs, {
hide: ["HTML"],
});
expect(queryAllByTestId(document.body, "lang-name")[0]).toBeInTheDocument(
"javascript",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).toBeInTheDocument(
"css",
);
expect(queryAllByTestId(document.body, "lang-name")[2]).not.toBeDefined();
// multiple languages passed
document.body.innerHTML = renderTopLanguages(langs, {
hide: ["HTML", "css"],
});
expect(queryAllByTestId(document.body, "lang-name")[0]).toBeInTheDocument(
"javascript",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).not.toBeDefined();
});
it("should resize the height correctly depending on langs", () => {
document.body.innerHTML = renderTopLanguages(langs, {});
expect(document.querySelector("svg")).toHaveAttribute("height", "205");
document.body.innerHTML = renderTopLanguages(
{
...langs,
python: {
color: "#ff0",
name: "python",
size: 100,
},
},
{},
);
expect(document.querySelector("svg")).toHaveAttribute("height", "245");
});
it("should render with custom width set", () => {
document.body.innerHTML = renderTopLanguages(langs, {});
expect(document.querySelector("svg")).toHaveAttribute("width", "300");
document.body.innerHTML = renderTopLanguages(langs, { card_width: 400 });
expect(document.querySelector("svg")).toHaveAttribute("width", "400");
});
it("should render with min width", () => {
document.body.innerHTML = renderTopLanguages(langs, { card_width: 190 });
expect(document.querySelector("svg")).toHaveAttribute(
"width",
MIN_CARD_WIDTH.toString(),
);
document.body.innerHTML = renderTopLanguages(langs, { card_width: 100 });
expect(document.querySelector("svg")).toHaveAttribute(
"width",
MIN_CARD_WIDTH.toString(),
);
});
it("should render default colors properly", () => {
document.body.innerHTML = renderTopLanguages(langs);
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.textContent);
const headerStyles = stylesObject[":host"][".header "];
const langNameStyles = stylesObject[":host"][".lang-name "];
expect(headerStyles.fill.trim()).toBe("#2f80ed");
expect(langNameStyles.fill.trim()).toBe("#434d58");
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#fffefe",
);
});
it("should render custom colors properly", () => {
const customColors = {
title_color: "5a0",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderTopLanguages(langs, { ...customColors });
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerStyles = stylesObject[":host"][".header "];
const langNameStyles = stylesObject[":host"][".lang-name "];
expect(headerStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(langNameStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render custom colors with themes", () => {
document.body.innerHTML = renderTopLanguages(langs, {
title_color: "5a0",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerStyles = stylesObject[":host"][".header "];
const langNameStyles = stylesObject[":host"][".lang-name "];
expect(headerStyles.fill.trim()).toBe("#5a0");
expect(langNameStyles.fill.trim()).toBe(`#${themes.radical.text_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should render with all the themes", () => {
Object.keys(themes).forEach((name) => {
document.body.innerHTML = renderTopLanguages(langs, {
theme: name,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerStyles = stylesObject[":host"][".header "];
const langNameStyles = stylesObject[":host"][".lang-name "];
expect(headerStyles.fill.trim()).toBe(`#${themes[name].title_color}`);
expect(langNameStyles.fill.trim()).toBe(`#${themes[name].text_color}`);
const backgroundElement = queryByTestId(document.body, "card-bg");
const backgroundElementFill = backgroundElement.getAttribute("fill");
expect([`#${themes[name].bg_color}`, "url(#gradient)"]).toContain(
backgroundElementFill,
);
});
});
it("should render with layout compact", () => {
document.body.innerHTML = renderTopLanguages(langs, { layout: "compact" });
expect(queryByTestId(document.body, "header")).toHaveTextContent(
"Most Used Languages",
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 40.00%",
);
expect(queryAllByTestId(document.body, "lang-progress")[0]).toHaveAttribute(
"width",
"100",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 40.00%",
);
expect(queryAllByTestId(document.body, "lang-progress")[1]).toHaveAttribute(
"width",
"100",
);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 20.00%",
);
expect(queryAllByTestId(document.body, "lang-progress")[2]).toHaveAttribute(
"width",
"50",
);
});
it("should render with layout donut", () => {
document.body.innerHTML = renderTopLanguages(langs, { layout: "donut" });
expect(queryByTestId(document.body, "header")).toHaveTextContent(
"Most Used Languages",
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 40.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[0]).toHaveAttribute(
"size",
"40",
);
const d = getNumbersFromSvgPathDefinitionAttribute(
queryAllByTestId(document.body, "lang-donut")[0].getAttribute("d"),
);
const center = { x: d[7], y: d[7] };
const HTMLLangPercent = langPercentFromDonutLayoutSvg(
queryAllByTestId(document.body, "lang-donut")[0].getAttribute("d"),
center.x,
center.y,
);
expect(HTMLLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 40.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[1]).toHaveAttribute(
"size",
"40",
);
const javascriptLangPercent = langPercentFromDonutLayoutSvg(
queryAllByTestId(document.body, "lang-donut")[1].getAttribute("d"),
center.x,
center.y,
);
expect(javascriptLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 20.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[2]).toHaveAttribute(
"size",
"20",
);
const cssLangPercent = langPercentFromDonutLayoutSvg(
queryAllByTestId(document.body, "lang-donut")[2].getAttribute("d"),
center.x,
center.y,
);
expect(cssLangPercent).toBeCloseTo(20);
expect(HTMLLangPercent + javascriptLangPercent + cssLangPercent).toBe(100);
// Should render full donut (circle) if one language is 100%.
document.body.innerHTML = renderTopLanguages(
{ HTML: langs.HTML },
{ layout: "donut" },
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 100.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[0]).toHaveAttribute(
"size",
"100",
);
expect(queryAllByTestId(document.body, "lang-donut")).toHaveLength(1);
expect(queryAllByTestId(document.body, "lang-donut")[0].tagName).toBe(
"circle",
);
});
it("should render with layout donut vertical", () => {
document.body.innerHTML = renderTopLanguages(langs, {
layout: "donut-vertical",
});
expect(queryByTestId(document.body, "header")).toHaveTextContent(
"Most Used Languages",
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 40.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[0]).toHaveAttribute(
"size",
"40",
);
const totalCircleLength = queryAllByTestId(
document.body,
"lang-donut",
)[0].getAttribute("stroke-dasharray");
const HTMLLangPercent = langPercentFromDonutVerticalLayoutSvg(
queryAllByTestId(document.body, "lang-donut")[1].getAttribute(
"stroke-dashoffset",
) -
queryAllByTestId(document.body, "lang-donut")[0].getAttribute(
"stroke-dashoffset",
),
totalCircleLength,
);
expect(HTMLLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 40.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[1]).toHaveAttribute(
"size",
"40",
);
const javascriptLangPercent = langPercentFromDonutVerticalLayoutSvg(
queryAllByTestId(document.body, "lang-donut")[2].getAttribute(
"stroke-dashoffset",
) -
queryAllByTestId(document.body, "lang-donut")[1].getAttribute(
"stroke-dashoffset",
),
totalCircleLength,
);
expect(javascriptLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 20.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[2]).toHaveAttribute(
"size",
"20",
);
const cssLangPercent = langPercentFromDonutVerticalLayoutSvg(
totalCircleLength -
queryAllByTestId(document.body, "lang-donut")[2].getAttribute(
"stroke-dashoffset",
),
totalCircleLength,
);
expect(cssLangPercent).toBeCloseTo(20);
expect(HTMLLangPercent + javascriptLangPercent + cssLangPercent).toBe(100);
});
it("should render with layout donut vertical full donut circle of one language is 100%", () => {
document.body.innerHTML = renderTopLanguages(
{ HTML: langs.HTML },
{ layout: "donut-vertical" },
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 100.00%",
);
expect(queryAllByTestId(document.body, "lang-donut")[0]).toHaveAttribute(
"size",
"100",
);
const totalCircleLength = queryAllByTestId(
document.body,
"lang-donut",
)[0].getAttribute("stroke-dasharray");
const HTMLLangPercent = langPercentFromDonutVerticalLayoutSvg(
totalCircleLength -
queryAllByTestId(document.body, "lang-donut")[0].getAttribute(
"stroke-dashoffset",
),
totalCircleLength,
);
expect(HTMLLangPercent).toBeCloseTo(100);
});
it("should render with layout pie", () => {
document.body.innerHTML = renderTopLanguages(langs, { layout: "pie" });
expect(queryByTestId(document.body, "header")).toHaveTextContent(
"Most Used Languages",
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 40.00%",
);
expect(queryAllByTestId(document.body, "lang-pie")[0]).toHaveAttribute(
"size",
"40",
);
const d = getNumbersFromSvgPathDefinitionAttribute(
queryAllByTestId(document.body, "lang-pie")[0].getAttribute("d"),
);
const center = { x: d[0], y: d[1] };
const HTMLLangPercent = langPercentFromPieLayoutSvg(
queryAllByTestId(document.body, "lang-pie")[0].getAttribute("d"),
center.x,
center.y,
);
expect(HTMLLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 40.00%",
);
expect(queryAllByTestId(document.body, "lang-pie")[1]).toHaveAttribute(
"size",
"40",
);
const javascriptLangPercent = langPercentFromPieLayoutSvg(
queryAllByTestId(document.body, "lang-pie")[1].getAttribute("d"),
center.x,
center.y,
);
expect(javascriptLangPercent).toBeCloseTo(40);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 20.00%",
);
expect(queryAllByTestId(document.body, "lang-pie")[2]).toHaveAttribute(
"size",
"20",
);
const cssLangPercent = langPercentFromPieLayoutSvg(
queryAllByTestId(document.body, "lang-pie")[2].getAttribute("d"),
center.x,
center.y,
);
expect(cssLangPercent).toBeCloseTo(20);
expect(HTMLLangPercent + javascriptLangPercent + cssLangPercent).toBe(100);
// Should render full pie (circle) if one language is 100%.
document.body.innerHTML = renderTopLanguages(
{ HTML: langs.HTML },
{ layout: "pie" },
);
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 100.00%",
);
expect(queryAllByTestId(document.body, "lang-pie")[0]).toHaveAttribute(
"size",
"100",
);
expect(queryAllByTestId(document.body, "lang-pie")).toHaveLength(1);
expect(queryAllByTestId(document.body, "lang-pie")[0].tagName).toBe(
"circle",
);
});
it("should render a translated title", () => {
document.body.innerHTML = renderTopLanguages(langs, { locale: "cn" });
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"最常用的语言",
);
});
it("should render without rounding", () => {
document.body.innerHTML = renderTopLanguages(langs, { border_radius: "0" });
expect(document.querySelector("rect")).toHaveAttribute("rx", "0");
document.body.innerHTML = renderTopLanguages(langs, {});
expect(document.querySelector("rect")).toHaveAttribute("rx", "4.5");
});
it("should render langs with specified langs_count", () => {
const options = {
langs_count: 1,
};
document.body.innerHTML = renderTopLanguages(langs, { ...options });
expect(queryAllByTestId(document.body, "lang-name").length).toBe(
options.langs_count,
);
});
it("should render langs with specified langs_count even when hide is set", () => {
const options = {
hide: ["HTML"],
langs_count: 2,
};
document.body.innerHTML = renderTopLanguages(langs, { ...options });
expect(queryAllByTestId(document.body, "lang-name").length).toBe(
options.langs_count,
);
});
it('should show "No languages data." message instead of empty card when nothing to show', () => {
document.body.innerHTML = renderTopLanguages({});
expect(document.querySelector(".stat").textContent).toBe(
"No languages data.",
);
});
it("should show proper stats format", () => {
document.body.innerHTML = renderTopLanguages(langs, {
layout: "compact",
stats_format: "percentages",
});
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 40.00%",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 40.00%",
);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 20.00%",
);
document.body.innerHTML = renderTopLanguages(langs, {
layout: "compact",
stats_format: "bytes",
});
expect(queryAllByTestId(document.body, "lang-name")[0]).toHaveTextContent(
"HTML 200.0 B",
);
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
"javascript 200.0 B",
);
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
"css 100.0 B",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fetchStats.test.js | tests/fetchStats.test.js | import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { calculateRank } from "../src/calculateRank.js";
import { fetchStats } from "../src/fetchers/stats.js";
// Test parameters.
const data_stats = {
data: {
user: {
name: "Anurag Hazra",
repositoriesContributedTo: { totalCount: 61 },
commits: {
totalCommitContributions: 100,
},
reviews: {
totalPullRequestReviewContributions: 50,
},
pullRequests: { totalCount: 300 },
mergedPullRequests: { totalCount: 240 },
openIssues: { totalCount: 100 },
closedIssues: { totalCount: 100 },
followers: { totalCount: 100 },
repositoryDiscussions: { totalCount: 10 },
repositoryDiscussionComments: { totalCount: 40 },
repositories: {
totalCount: 5,
nodes: [
{ name: "test-repo-1", stargazers: { totalCount: 100 } },
{ name: "test-repo-2", stargazers: { totalCount: 100 } },
{ name: "test-repo-3", stargazers: { totalCount: 100 } },
],
pageInfo: {
hasNextPage: true,
endCursor: "cursor",
},
},
},
},
};
const data_year2003 = JSON.parse(JSON.stringify(data_stats));
data_year2003.data.user.commits.totalCommitContributions = 428;
const data_without_pull_requests = {
data: {
user: {
...data_stats.data.user,
pullRequests: { totalCount: 0 },
mergedPullRequests: { totalCount: 0 },
},
},
};
const data_repo = {
data: {
user: {
repositories: {
nodes: [
{ name: "test-repo-4", stargazers: { totalCount: 50 } },
{ name: "test-repo-5", stargazers: { totalCount: 50 } },
],
pageInfo: {
hasNextPage: false,
endCursor: "cursor",
},
},
},
},
};
const data_repo_zero_stars = {
data: {
user: {
repositories: {
nodes: [
{ name: "test-repo-1", stargazers: { totalCount: 100 } },
{ name: "test-repo-2", stargazers: { totalCount: 100 } },
{ name: "test-repo-3", stargazers: { totalCount: 100 } },
{ name: "test-repo-4", stargazers: { totalCount: 0 } },
{ name: "test-repo-5", stargazers: { totalCount: 0 } },
],
pageInfo: {
hasNextPage: true,
endCursor: "cursor",
},
},
},
},
};
const error = {
errors: [
{
type: "NOT_FOUND",
path: ["user"],
locations: [],
message: "Could not resolve to a User with the login of 'noname'.",
},
],
};
const mock = new MockAdapter(axios);
beforeEach(() => {
process.env.FETCH_MULTI_PAGE_STARS = "false"; // Set to `false` to fetch only one page of stars.
mock.onPost("https://api.github.com/graphql").reply((cfg) => {
let req = JSON.parse(cfg.data);
if (
req.variables &&
req.variables.startTime &&
req.variables.startTime.startsWith("2003")
) {
return [200, data_year2003];
}
return [
200,
req.query.includes("totalCommitContributions") ? data_stats : data_repo,
];
});
});
afterEach(() => {
mock.reset();
});
describe("Test fetchStats", () => {
it("should fetch correct stats", async () => {
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should stop fetching when there are repos with zero stars", async () => {
mock.reset();
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, data_stats)
.onPost("https://api.github.com/graphql")
.replyOnce(200, data_repo_zero_stars);
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should throw error", async () => {
mock.reset();
mock.onPost("https://api.github.com/graphql").reply(200, error);
await expect(fetchStats("anuraghazra")).rejects.toThrow(
"Could not resolve to a User with the login of 'noname'.",
);
});
it("should fetch total commits", async () => {
mock
.onGet("https://api.github.com/search/commits?q=author:anuraghazra")
.reply(200, { total_count: 1000 });
let stats = await fetchStats("anuraghazra", true);
const rank = calculateRank({
all_commits: true,
commits: 1000,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 1000,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should throw specific error when include_all_commits true and invalid username", async () => {
expect(fetchStats("asdf///---", true)).rejects.toThrow(
new Error("Invalid username provided."),
);
});
it("should throw specific error when include_all_commits true and API returns error", async () => {
mock
.onGet("https://api.github.com/search/commits?q=author:anuraghazra")
.reply(200, { error: "Some test error message" });
expect(fetchStats("anuraghazra", true)).rejects.toThrow(
new Error("Could not fetch total commits."),
);
});
it("should exclude stars of the `test-repo-1` repository", async () => {
mock
.onGet("https://api.github.com/search/commits?q=author:anuraghazra")
.reply(200, { total_count: 1000 });
let stats = await fetchStats("anuraghazra", true, ["test-repo-1"]);
const rank = calculateRank({
all_commits: true,
commits: 1000,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 200,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 1000,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 200,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should fetch two pages of stars if 'FETCH_MULTI_PAGE_STARS' env variable is set to `true`", async () => {
process.env.FETCH_MULTI_PAGE_STARS = true;
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 400,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 400,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should fetch one page of stars if 'FETCH_MULTI_PAGE_STARS' env variable is set to `false`", async () => {
process.env.FETCH_MULTI_PAGE_STARS = "false";
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should fetch one page of stars if 'FETCH_MULTI_PAGE_STARS' env variable is not set", async () => {
process.env.FETCH_MULTI_PAGE_STARS = undefined;
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should not fetch additional stats data when it not requested", async () => {
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should fetch additional stats when it requested", async () => {
let stats = await fetchStats("anuraghazra", false, [], true, true, true);
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 240,
mergedPRsPercentage: 80,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 10,
totalDiscussionsAnswered: 40,
rank,
});
});
it("should get commits of provided year", async () => {
let stats = await fetchStats(
"anuraghazra",
false,
[],
false,
false,
false,
2003,
);
const rank = calculateRank({
all_commits: false,
commits: 428,
prs: 300,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 428,
totalIssues: 200,
totalPRs: 300,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
it("should return correct data when user don't have any pull requests", async () => {
mock.reset();
mock
.onPost("https://api.github.com/graphql")
.reply(200, data_without_pull_requests);
const stats = await fetchStats("anuraghazra", false, [], true);
const rank = calculateRank({
all_commits: false,
commits: 100,
prs: 0,
reviews: 50,
issues: 200,
repos: 5,
stars: 300,
followers: 100,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 0,
totalPRsMerged: 0,
mergedPRsPercentage: 0,
totalReviews: 50,
totalStars: 300,
totalDiscussionsStarted: 0,
totalDiscussionsAnswered: 0,
rank,
});
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/retryer.test.js | tests/retryer.test.js | // @ts-check
import { describe, expect, it, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import { RETRIES, retryer } from "../src/common/retryer.js";
import { logger } from "../src/common/log.js";
const fetcher = jest.fn((variables, token) => {
logger.log(variables, token);
return new Promise((res) => res({ data: "ok" }));
});
const fetcherFail = jest.fn(() => {
return new Promise((res) =>
res({ data: { errors: [{ type: "RATE_LIMITED" }] } }),
);
});
const fetcherFailOnSecondTry = jest.fn((_vars, _token, retries) => {
return new Promise((res) => {
// faking rate limit
// @ts-ignore
if (retries < 1) {
return res({ data: { errors: [{ type: "RATE_LIMITED" }] } });
}
return res({ data: "ok" });
});
});
const fetcherFailWithMessageBasedRateLimitErr = jest.fn(
(_vars, _token, retries) => {
return new Promise((res) => {
// faking rate limit
// @ts-ignore
if (retries < 1) {
return res({
data: {
errors: [
{
type: "ASDF",
message: "API rate limit already exceeded for user ID 11111111",
},
],
},
});
}
return res({ data: "ok" });
});
},
);
describe("Test Retryer", () => {
it("retryer should return value and have zero retries on first try", async () => {
let res = await retryer(fetcher, {});
expect(fetcher).toHaveBeenCalledTimes(1);
expect(res).toStrictEqual({ data: "ok" });
});
it("retryer should return value and have 2 retries", async () => {
let res = await retryer(fetcherFailOnSecondTry, {});
expect(fetcherFailOnSecondTry).toHaveBeenCalledTimes(2);
expect(res).toStrictEqual({ data: "ok" });
});
it("retryer should return value and have 2 retries with message based rate limit error", async () => {
let res = await retryer(fetcherFailWithMessageBasedRateLimitErr, {});
expect(fetcherFailWithMessageBasedRateLimitErr).toHaveBeenCalledTimes(2);
expect(res).toStrictEqual({ data: "ok" });
});
it("retryer should throw specific error if maximum retries reached", async () => {
try {
await retryer(fetcherFail, {});
} catch (err) {
expect(fetcherFail).toHaveBeenCalledTimes(RETRIES + 1);
// @ts-ignore
expect(err.message).toBe("Downtime due to GitHub API rate limiting");
}
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/pat-info.test.js | tests/pat-info.test.js | /**
* @file Tests for the status/pat-info cloud function.
*/
import dotenv from "dotenv";
dotenv.config();
import {
afterEach,
beforeAll,
describe,
expect,
it,
jest,
} from "@jest/globals";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import patInfo, { RATE_LIMIT_SECONDS } from "../api/status/pat-info.js";
const mock = new MockAdapter(axios);
const successData = {
data: {
rateLimit: {
remaining: 4986,
},
},
};
const faker = (query) => {
const req = {
query: { ...query },
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
return { req, res };
};
const rate_limit_error = {
errors: [
{
type: "RATE_LIMITED",
message: "API rate limit exceeded for user ID.",
},
],
data: {
rateLimit: {
resetAt: Date.now(),
},
},
};
const other_error = {
errors: [
{
type: "SOME_ERROR",
message: "This is a error",
},
],
};
const bad_credentials_error = {
message: "Bad credentials",
};
afterEach(() => {
mock.reset();
});
describe("Test /api/status/pat-info", () => {
beforeAll(() => {
// reset patenv first so that dotenv doesn't populate them with local envs
process.env = {};
process.env.PAT_1 = "testPAT1";
process.env.PAT_2 = "testPAT2";
process.env.PAT_3 = "testPAT3";
process.env.PAT_4 = "testPAT4";
});
it("should return only 'validPATs' if all PATs are valid", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, rate_limit_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: [],
exhaustedPATs: ["PAT_1"],
suspendedPATs: [],
errorPATs: [],
details: {
PAT_1: {
status: "exhausted",
remaining: 0,
resetIn: "0 minutes",
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should return `errorPATs` if a PAT causes an error to be thrown", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, other_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: [],
exhaustedPATs: [],
suspendedPATs: [],
errorPATs: ["PAT_1"],
details: {
PAT_1: {
status: "error",
error: {
type: "SOME_ERROR",
message: "This is a error",
},
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should return `expiredPaths` if a PAT returns a 'Bad credentials' error", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(404, bad_credentials_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: ["PAT_1"],
exhaustedPATs: [],
suspendedPATs: [],
errorPATs: [],
details: {
PAT_1: {
status: "expired",
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should throw an error if something goes wrong", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(
"Something went wrong: Network Error",
);
});
it("should have proper cache when no error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`],
]);
});
it("should have proper cache when error is thrown", async () => {
mock.reset();
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", "no-store"],
]);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/pin.test.js | tests/pin.test.js | // @ts-check
import { afterEach, describe, expect, it, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import pin from "../api/pin.js";
import { renderRepoCard } from "../src/cards/repo.js";
import { renderError } from "../src/common/render.js";
import { CACHE_TTL, DURATIONS } from "../src/common/cache.js";
const data_repo = {
repository: {
username: "anuraghazra",
name: "convoychat",
stargazers: {
totalCount: 38000,
},
description: "Help us take over the world! React + TS + GraphQL Chat App",
primaryLanguage: {
color: "#2b7489",
id: "MDg6TGFuZ3VhZ2UyODc=",
name: "TypeScript",
},
forkCount: 100,
isTemplate: false,
},
};
const data_user = {
data: {
user: { repository: data_repo.repository },
organization: null,
},
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test /api/pin", () => {
it("should test the request", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
// @ts-ignore
renderRepoCard({
...data_repo.repository,
starCount: data_repo.repository.stargazers.totalCount,
}),
);
});
it("should get the query options", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
full_name: "1",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderRepoCard(
// @ts-ignore
{
...data_repo.repository,
starCount: data_repo.repository.stargazers.totalCount,
},
{ ...req.query },
),
);
});
it("should render error card if user repo not found", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock
.onPost("https://api.github.com/graphql")
.reply(200, { data: { user: { repository: null }, organization: null } });
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({ message: "User Repository Not found" }),
);
});
it("should render error card if org repo not found", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock
.onPost("https://api.github.com/graphql")
.reply(200, { data: { user: null, organization: { repository: null } } });
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({ message: "Organization Repository Not found" }),
);
});
it("should render error card if username in blacklist", async () => {
const req = {
query: {
username: "renovate-bot",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "This username is blacklisted",
secondaryMessage: "Please deploy your own instance",
renderOptions: { show_repo_link: false },
}),
);
});
it("should render error card if wrong locale provided", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
locale: "asdf",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
}),
);
});
it("should render error card if missing required parameters", async () => {
const req = {
query: {},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message:
'Missing params "username", "repo" make sure you pass the parameters in URL',
secondaryMessage: "/api/pin?username=USERNAME&repo=REPO_NAME",
renderOptions: { show_repo_link: false },
}),
);
});
it("should have proper cache", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
await pin(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.setHeader).toHaveBeenCalledWith(
"Cache-Control",
`max-age=${CACHE_TTL.PIN_CARD.DEFAULT}, ` +
`s-maxage=${CACHE_TTL.PIN_CARD.DEFAULT}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/card.test.js | tests/card.test.js | import { describe, expect, it } from "@jest/globals";
import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom";
import { cssToObject } from "@uppercod/css-to-object";
import { Card } from "../src/common/Card.js";
import { icons } from "../src/common/icons.js";
import { getCardColors } from "../src/common/color.js";
describe("Card", () => {
it("should hide border", () => {
const card = new Card({});
card.setHideBorder(true);
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"stroke-opacity",
"0",
);
});
it("should not hide border", () => {
const card = new Card({});
card.setHideBorder(false);
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"stroke-opacity",
"1",
);
});
it("should have a custom title", () => {
const card = new Card({
customTitle: "custom title",
defaultTitle: "default title",
});
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-title")).toHaveTextContent(
"custom title",
);
});
it("should set custom title", () => {
const card = new Card({});
card.setTitle("custom title");
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-title")).toHaveTextContent(
"custom title",
);
});
it("should hide title", () => {
const card = new Card({});
card.setHideTitle(true);
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-title")).toBeNull();
});
it("should not hide title", () => {
const card = new Card({});
card.setHideTitle(false);
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-title")).toBeInTheDocument();
});
it("title should have prefix icon", () => {
const card = new Card({ title: "ok", titlePrefixIcon: icons.contribs });
document.body.innerHTML = card.render(``);
expect(document.getElementsByClassName("icon")[0]).toBeInTheDocument();
});
it("title should not have prefix icon", () => {
const card = new Card({ title: "ok" });
document.body.innerHTML = card.render(``);
expect(document.getElementsByClassName("icon")[0]).toBeUndefined();
});
it("should have proper height, width", () => {
const card = new Card({ height: 200, width: 200, title: "ok" });
document.body.innerHTML = card.render(``);
expect(document.getElementsByTagName("svg")[0]).toHaveAttribute(
"height",
"200",
);
expect(document.getElementsByTagName("svg")[0]).toHaveAttribute(
"width",
"200",
);
});
it("should have less height after title is hidden", () => {
const card = new Card({ height: 200, title: "ok" });
card.setHideTitle(true);
document.body.innerHTML = card.render(``);
expect(document.getElementsByTagName("svg")[0]).toHaveAttribute(
"height",
"170",
);
});
it("main-card-body should have proper when title is visible", () => {
const card = new Card({ height: 200 });
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "main-card-body")).toHaveAttribute(
"transform",
"translate(0, 55)",
);
});
it("main-card-body should have proper position after title is hidden", () => {
const card = new Card({ height: 200 });
card.setHideTitle(true);
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "main-card-body")).toHaveAttribute(
"transform",
"translate(0, 25)",
);
});
it("should render with correct colors", () => {
// returns theme based colors with proper overrides and defaults
const { titleColor, textColor, iconColor, bgColor } = getCardColors({
title_color: "f00",
icon_color: "0f0",
text_color: "00f",
bg_color: "fff",
theme: "default",
});
const card = new Card({
height: 200,
colors: {
titleColor,
textColor,
iconColor,
bgColor,
},
});
document.body.innerHTML = card.render(``);
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
expect(headerClassStyles["fill"].trim()).toBe("#f00");
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#fff",
);
});
it("should render gradient backgrounds", () => {
const { titleColor, textColor, iconColor, bgColor } = getCardColors({
title_color: "f00",
icon_color: "0f0",
text_color: "00f",
bg_color: "90,fff,000,f00",
theme: "default",
});
const card = new Card({
height: 200,
colors: {
titleColor,
textColor,
iconColor,
bgColor,
},
});
document.body.innerHTML = card.render(``);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"url(#gradient)",
);
expect(document.querySelector("defs #gradient")).toHaveAttribute(
"gradientTransform",
"rotate(90)",
);
expect(
document.querySelector("defs #gradient stop:nth-child(1)"),
).toHaveAttribute("stop-color", "#fff");
expect(
document.querySelector("defs #gradient stop:nth-child(2)"),
).toHaveAttribute("stop-color", "#000");
expect(
document.querySelector("defs #gradient stop:nth-child(3)"),
).toHaveAttribute("stop-color", "#f00");
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/ops.test.js | tests/ops.test.js | import { describe, expect, it } from "@jest/globals";
import {
parseBoolean,
parseArray,
clampValue,
lowercaseTrim,
chunkArray,
parseEmojis,
dateDiff,
} from "../src/common/ops.js";
describe("Test ops.js", () => {
it("should test parseBoolean", () => {
expect(parseBoolean(true)).toBe(true);
expect(parseBoolean(false)).toBe(false);
expect(parseBoolean("true")).toBe(true);
expect(parseBoolean("false")).toBe(false);
expect(parseBoolean("True")).toBe(true);
expect(parseBoolean("False")).toBe(false);
expect(parseBoolean("TRUE")).toBe(true);
expect(parseBoolean("FALSE")).toBe(false);
expect(parseBoolean("1")).toBe(undefined);
expect(parseBoolean("0")).toBe(undefined);
expect(parseBoolean("")).toBe(undefined);
// @ts-ignore
expect(parseBoolean(undefined)).toBe(undefined);
});
it("should test parseArray", () => {
expect(parseArray("a,b,c")).toEqual(["a", "b", "c"]);
expect(parseArray("a, b, c")).toEqual(["a", " b", " c"]); // preserves spaces
expect(parseArray("")).toEqual([]);
// @ts-ignore
expect(parseArray(undefined)).toEqual([]);
});
it("should test clampValue", () => {
expect(clampValue(5, 1, 10)).toBe(5);
expect(clampValue(0, 1, 10)).toBe(1);
expect(clampValue(15, 1, 10)).toBe(10);
// string inputs are coerced numerically by Math.min/Math.max
// @ts-ignore
expect(clampValue("7", 1, 10)).toBe(7);
// non-numeric and NaN fall back to min
// @ts-ignore
expect(clampValue("abc", 1, 10)).toBe(1);
expect(clampValue(NaN, 2, 5)).toBe(2);
});
it("should test lowercaseTrim", () => {
expect(lowercaseTrim(" Hello World ")).toBe("hello world");
expect(lowercaseTrim("already lower")).toBe("already lower");
});
it("should test chunkArray", () => {
expect(chunkArray([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
expect(chunkArray([1, 2, 3, 4, 5], 1)).toEqual([[1], [2], [3], [4], [5]]);
expect(chunkArray([1, 2, 3, 4, 5], 10)).toEqual([[1, 2, 3, 4, 5]]);
});
it("should test parseEmojis", () => {
// unknown emoji name is stripped
expect(parseEmojis("Hello :nonexistent:")).toBe("Hello ");
// common emoji names should be replaced (at least token removed)
const out = parseEmojis("I :heart: OSS");
expect(out).not.toContain(":heart:");
expect(out.startsWith("I ")).toBe(true);
expect(out.endsWith(" OSS")).toBe(true);
expect(() => parseEmojis("")).toThrow(/parseEmoji/);
// @ts-ignore
expect(() => parseEmojis()).toThrow(/parseEmoji/);
});
it("should test dateDiff", () => {
const a = new Date("2020-01-01T00:10:00Z");
const b = new Date("2020-01-01T00:00:00Z");
expect(dateDiff(a, b)).toBe(10);
const c = new Date("2020-01-01T00:00:00Z");
const d = new Date("2020-01-01T00:10:30Z");
// rounds to nearest minute
expect(dateDiff(c, d)).toBe(-10);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/renderRepoCard.test.js | tests/renderRepoCard.test.js | import { describe, expect, it } from "@jest/globals";
import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom";
import { cssToObject } from "@uppercod/css-to-object";
import { renderRepoCard } from "../src/cards/repo.js";
import { themes } from "../themes/index.js";
const data_repo = {
repository: {
nameWithOwner: "anuraghazra/convoychat",
name: "convoychat",
description: "Help us take over the world! React + TS + GraphQL Chat App",
primaryLanguage: {
color: "#2b7489",
id: "MDg6TGFuZ3VhZ2UyODc=",
name: "TypeScript",
},
starCount: 38000,
forkCount: 100,
},
};
describe("Test renderRepoCard", () => {
it("should render correctly", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository);
const [header] = document.getElementsByClassName("header");
expect(header).toHaveTextContent("convoychat");
expect(header).not.toHaveTextContent("anuraghazra");
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"Help us take over the world! React + TS + GraphQL Chat App",
);
expect(queryByTestId(document.body, "stargazers")).toHaveTextContent("38k");
expect(queryByTestId(document.body, "forkcount")).toHaveTextContent("100");
expect(queryByTestId(document.body, "lang-name")).toHaveTextContent(
"TypeScript",
);
expect(queryByTestId(document.body, "lang-color")).toHaveAttribute(
"fill",
"#2b7489",
);
});
it("should display username in title (full repo name)", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository, {
show_owner: true,
});
expect(document.getElementsByClassName("header")[0]).toHaveTextContent(
"anuraghazra/convoychat",
);
});
it("should trim header", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
name: "some-really-long-repo-name-for-test-purposes",
});
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"some-really-long-repo-name-for-test...",
);
});
it("should trim description", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
description:
"The quick brown fox jumps over the lazy dog is an English-language pangram—a sentence that contains all of the letters of the English alphabet",
});
expect(
document.getElementsByClassName("description")[0].children[0].textContent,
).toBe("The quick brown fox jumps over the lazy dog is an");
expect(
document.getElementsByClassName("description")[0].children[1].textContent,
).toBe("English-language pangram—a sentence that contains all");
// Should not trim
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
description: "Small text should not trim",
});
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"Small text should not trim",
);
});
it("should render emojis", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
description: "This is a text with a :poop: poo emoji",
});
// poop emoji may not show in all editors but it's there between "a" and "poo"
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"This is a text with a 💩 poo emoji",
);
});
it("should hide language if primaryLanguage is null & fallback to correct values", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
primaryLanguage: null,
});
expect(queryByTestId(document.body, "primary-lang")).toBeNull();
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
primaryLanguage: { color: null, name: null },
});
expect(queryByTestId(document.body, "primary-lang")).toBeInTheDocument();
expect(queryByTestId(document.body, "lang-color")).toHaveAttribute(
"fill",
"#333",
);
expect(queryByTestId(document.body, "lang-name")).toHaveTextContent(
"Unspecified",
);
});
it("should render default colors properly", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository);
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe("#2f80ed");
expect(descClassStyles.fill.trim()).toBe("#434d58");
expect(iconClassStyles.fill.trim()).toBe("#586069");
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#fffefe",
);
});
it("should render custom colors properly", () => {
const customColors = {
title_color: "5a0",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderRepoCard(data_repo.repository, {
...customColors,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(descClassStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${customColors.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render with all the themes", () => {
Object.keys(themes).forEach((name) => {
document.body.innerHTML = renderRepoCard(data_repo.repository, {
theme: name,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes[name].title_color}`,
);
expect(descClassStyles.fill.trim()).toBe(`#${themes[name].text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes[name].icon_color}`);
const backgroundElement = queryByTestId(document.body, "card-bg");
const backgroundElementFill = backgroundElement.getAttribute("fill");
expect([`#${themes[name].bg_color}`, "url(#gradient)"]).toContain(
backgroundElementFill,
);
});
});
it("should render custom colors with themes", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository, {
title_color: "5a0",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe("#5a0");
expect(descClassStyles.fill.trim()).toBe(`#${themes.radical.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should render custom colors with themes and fallback to default colors if invalid", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository, {
title_color: "invalid color",
text_color: "invalid color",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes.default.title_color}`,
);
expect(descClassStyles.fill.trim()).toBe(`#${themes.default.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should not render star count or fork count if either of the are zero", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
starCount: 0,
});
expect(queryByTestId(document.body, "stargazers")).toBeNull();
expect(queryByTestId(document.body, "forkcount")).toBeInTheDocument();
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
starCount: 1,
forkCount: 0,
});
expect(queryByTestId(document.body, "stargazers")).toBeInTheDocument();
expect(queryByTestId(document.body, "forkcount")).toBeNull();
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
starCount: 0,
forkCount: 0,
});
expect(queryByTestId(document.body, "stargazers")).toBeNull();
expect(queryByTestId(document.body, "forkcount")).toBeNull();
});
it("should render badges", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
isArchived: true,
});
expect(queryByTestId(document.body, "badge")).toHaveTextContent("Archived");
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
isTemplate: true,
});
expect(queryByTestId(document.body, "badge")).toHaveTextContent("Template");
});
it("should not render template", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
});
expect(queryByTestId(document.body, "badge")).toBeNull();
});
it("should render translated badges", () => {
document.body.innerHTML = renderRepoCard(
{
...data_repo.repository,
isArchived: true,
},
{
locale: "cn",
},
);
expect(queryByTestId(document.body, "badge")).toHaveTextContent("已归档");
document.body.innerHTML = renderRepoCard(
{
...data_repo.repository,
isTemplate: true,
},
{
locale: "cn",
},
);
expect(queryByTestId(document.body, "badge")).toHaveTextContent("模板");
});
it("should render without rounding", () => {
document.body.innerHTML = renderRepoCard(data_repo.repository, {
border_radius: "0",
});
expect(document.querySelector("rect")).toHaveAttribute("rx", "0");
document.body.innerHTML = renderRepoCard(data_repo.repository, {});
expect(document.querySelector("rect")).toHaveAttribute("rx", "4.5");
});
it("should fallback to default description", () => {
document.body.innerHTML = renderRepoCard({
...data_repo.repository,
description: undefined,
isArchived: true,
});
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"No description provided",
);
});
it("should have correct height with specified `description_lines_count` parameter", () => {
// Testing short description
document.body.innerHTML = renderRepoCard(data_repo.repository, {
description_lines_count: 1,
});
expect(document.querySelector("svg")).toHaveAttribute("height", "120");
document.body.innerHTML = renderRepoCard(data_repo.repository, {
description_lines_count: 3,
});
expect(document.querySelector("svg")).toHaveAttribute("height", "150");
// Testing long description
const longDescription =
"A tool that will make a lot of iPhone/iPad developers' life easier. It shares your app over-the-air in a WiFi network. Bonjour is used and no configuration is needed.";
document.body.innerHTML = renderRepoCard(
{ ...data_repo.repository, description: longDescription },
{
description_lines_count: 3,
},
);
expect(document.querySelector("svg")).toHaveAttribute("height", "150");
document.body.innerHTML = renderRepoCard(
{ ...data_repo.repository, description: longDescription },
{
description_lines_count: 1,
},
);
expect(document.querySelector("svg")).toHaveAttribute("height", "120");
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/html.test.js | tests/html.test.js | import { describe, expect, it } from "@jest/globals";
import { encodeHTML } from "../src/common/html.js";
describe("Test html.js", () => {
it("should test encodeHTML", () => {
expect(encodeHTML(`<html>hello world<,.#4^&^@%!))`)).toBe(
"<html>hello world<,.#4^&^@%!))",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/top-langs.test.js | tests/top-langs.test.js | // @ts-check
import { afterEach, describe, expect, it, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import topLangs from "../api/top-langs.js";
import { renderTopLanguages } from "../src/cards/top-languages.js";
import { renderError } from "../src/common/render.js";
import { CACHE_TTL, DURATIONS } from "../src/common/cache.js";
const data_langs = {
data: {
user: {
repositories: {
nodes: [
{
languages: {
edges: [{ size: 150, node: { color: "#0f0", name: "HTML" } }],
},
},
{
languages: {
edges: [{ size: 100, node: { color: "#0f0", name: "HTML" } }],
},
},
{
languages: {
edges: [
{ size: 100, node: { color: "#0ff", name: "javascript" } },
],
},
},
{
languages: {
edges: [
{ size: 100, node: { color: "#0ff", name: "javascript" } },
],
},
},
],
},
},
},
};
const error = {
errors: [
{
type: "NOT_FOUND",
path: ["user"],
locations: [],
message: "Could not fetch user",
},
],
};
const langs = {
HTML: {
color: "#0f0",
name: "HTML",
size: 250,
},
javascript: {
color: "#0ff",
name: "javascript",
size: 200,
},
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test /api/top-langs", () => {
it("should test the request", async () => {
const req = {
query: {
username: "anuraghazra",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(renderTopLanguages(langs));
});
it("should work with the query options", async () => {
const req = {
query: {
username: "anuraghazra",
hide_title: true,
card_width: 100,
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderTopLanguages(langs, {
hide_title: true,
card_width: 100,
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
}),
);
});
it("should render error card on user data fetch error", async () => {
const req = {
query: {
username: "anuraghazra",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, error);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: error.errors[0].message,
secondaryMessage:
"Make sure the provided username is not an organization",
}),
);
});
it("should render error card on incorrect layout input", async () => {
const req = {
query: {
username: "anuraghazra",
layout: ["pie"],
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Something went wrong",
secondaryMessage: "Incorrect layout input",
}),
);
});
it("should render error card if username in blacklist", async () => {
const req = {
query: {
username: "renovate-bot",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "This username is blacklisted",
secondaryMessage: "Please deploy your own instance",
renderOptions: { show_repo_link: false },
}),
);
});
it("should render error card if wrong locale provided", async () => {
const req = {
query: {
username: "anuraghazra",
locale: "asdf",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Something went wrong",
secondaryMessage: "Locale not found",
}),
);
});
it("should have proper cache", async () => {
const req = {
query: {
username: "anuraghazra",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
await topLangs(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.setHeader).toHaveBeenCalledWith(
"Cache-Control",
`max-age=${CACHE_TTL.TOP_LANGS_CARD.DEFAULT}, ` +
`s-maxage=${CACHE_TTL.TOP_LANGS_CARD.DEFAULT}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/renderWakatimeCard.test.js | tests/renderWakatimeCard.test.js | import { describe, expect, it } from "@jest/globals";
import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom";
import { renderWakatimeCard } from "../src/cards/wakatime.js";
import { wakaTimeData } from "./fetchWakatime.test.js";
describe("Test Render WakaTime Card", () => {
it("should render correctly", () => {
const card = renderWakatimeCard(wakaTimeData.data);
expect(card).toMatchSnapshot();
});
it("should render correctly with compact layout", () => {
const card = renderWakatimeCard(wakaTimeData.data, { layout: "compact" });
expect(card).toMatchSnapshot();
});
it("should render correctly with compact layout when langs_count is set", () => {
const card = renderWakatimeCard(wakaTimeData.data, {
layout: "compact",
langs_count: 2,
});
expect(card).toMatchSnapshot();
});
it("should hide languages when hide is passed", () => {
document.body.innerHTML = renderWakatimeCard(wakaTimeData.data, {
hide: ["YAML", "Other"],
});
expect(queryByTestId(document.body, /YAML/i)).toBeNull();
expect(queryByTestId(document.body, /Other/i)).toBeNull();
expect(queryByTestId(document.body, /TypeScript/i)).not.toBeNull();
});
it("should render translations", () => {
document.body.innerHTML = renderWakatimeCard({}, { locale: "cn" });
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"WakaTime 周统计",
);
expect(
document.querySelector('g[transform="translate(0, 0)"]>text.stat.bold')
.textContent,
).toBe("WakaTime 用户个人资料未公开");
});
it("should render without rounding", () => {
document.body.innerHTML = renderWakatimeCard(wakaTimeData.data, {
border_radius: "0",
});
expect(document.querySelector("rect")).toHaveAttribute("rx", "0");
document.body.innerHTML = renderWakatimeCard(wakaTimeData.data, {});
expect(document.querySelector("rect")).toHaveAttribute("rx", "4.5");
});
it('should show "no coding activity this week" message when there has not been activity', () => {
document.body.innerHTML = renderWakatimeCard(
{
...wakaTimeData.data,
languages: undefined,
},
{},
);
expect(document.querySelector(".stat").textContent).toBe(
"No coding activity this week",
);
});
it('should show "no coding activity this week" message when using compact layout and there has not been activity', () => {
document.body.innerHTML = renderWakatimeCard(
{
...wakaTimeData.data,
languages: undefined,
},
{
layout: "compact",
},
);
expect(document.querySelector(".stat").textContent).toBe(
"No coding activity this week",
);
});
it("should render correctly with percent display format", () => {
const card = renderWakatimeCard(wakaTimeData.data, {
display_format: "percent",
});
expect(card).toMatchSnapshot();
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/render.test.js | tests/render.test.js | // @ts-check
import { describe, expect, it } from "@jest/globals";
import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom/jest-globals";
import { renderError } from "../src/common/render.js";
describe("Test render.js", () => {
it("should test renderError", () => {
document.body.innerHTML = renderError({ message: "Something went wrong" });
expect(
queryByTestId(document.body, "message")?.children[0],
).toHaveTextContent(/Something went wrong/gim);
expect(
queryByTestId(document.body, "message")?.children[1],
).toBeEmptyDOMElement();
// Secondary message
document.body.innerHTML = renderError({
message: "Something went wrong",
secondaryMessage: "Secondary Message",
});
expect(
queryByTestId(document.body, "message")?.children[1],
).toHaveTextContent(/Secondary Message/gim);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fetchWakatime.test.js | tests/fetchWakatime.test.js | import { afterEach, describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { fetchWakatimeStats } from "../src/fetchers/wakatime.js";
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
const wakaTimeData = {
data: {
categories: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "Coding",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
daily_average: 16095,
daily_average_including_other_language: 16329,
days_including_holidays: 7,
days_minus_holidays: 5,
editors: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "VS Code",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
holidays: 2,
human_readable_daily_average: "4 hrs 28 mins",
human_readable_daily_average_including_other_language: "4 hrs 32 mins",
human_readable_total: "22 hrs 21 mins",
human_readable_total_including_other_language: "22 hrs 40 mins",
id: "random hash",
is_already_updating: false,
is_coding_activity_visible: true,
is_including_today: false,
is_other_usage_visible: true,
is_stuck: false,
is_up_to_date: true,
languages: [
{
digital: "0:19",
hours: 0,
minutes: 19,
name: "Other",
percent: 1.43,
text: "19 mins",
total_seconds: 1170.434361,
},
{
digital: "0:01",
hours: 0,
minutes: 1,
name: "TypeScript",
percent: 0.1,
text: "1 min",
total_seconds: 83.293809,
},
{
digital: "0:00",
hours: 0,
minutes: 0,
name: "YAML",
percent: 0.07,
text: "0 secs",
total_seconds: 54.975151,
},
],
operating_systems: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "Mac",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
percent_calculated: 100,
range: "last_7_days",
status: "ok",
timeout: 15,
total_seconds: 80473.135716,
total_seconds_including_other_language: 81643.570077,
user_id: "random hash",
username: "anuraghazra",
writes_only: false,
},
};
describe("WakaTime fetcher", () => {
it("should fetch correct WakaTime data", async () => {
const username = "anuraghazra";
mock
.onGet(
`https://wakatime.com/api/v1/users/${username}/stats?is_including_today=true`,
)
.reply(200, wakaTimeData);
const repo = await fetchWakatimeStats({ username });
expect(repo).toStrictEqual(wakaTimeData.data);
});
it("should throw error if username param missing", async () => {
mock.onGet(/\/https:\/\/wakatime\.com\/api/).reply(404, wakaTimeData);
await expect(fetchWakatimeStats("noone")).rejects.toThrow(
'Missing params "username" make sure you pass the parameters in URL',
);
});
it("should throw error if username is not found", async () => {
mock.onGet(/\/https:\/\/wakatime\.com\/api/).reply(404, wakaTimeData);
await expect(fetchWakatimeStats({ username: "noone" })).rejects.toThrow(
"Could not resolve to a User with the login of 'noone'",
);
});
});
export { wakaTimeData };
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/renderStatsCard.test.js | tests/renderStatsCard.test.js | import { describe, expect, it } from "@jest/globals";
import {
getByTestId,
queryAllByTestId,
queryByTestId,
} from "@testing-library/dom";
import "@testing-library/jest-dom";
import { cssToObject } from "@uppercod/css-to-object";
import { renderStatsCard } from "../src/cards/stats.js";
import { CustomError } from "../src/common/error.js";
import { themes } from "../themes/index.js";
const stats = {
name: "Anurag Hazra",
totalStars: 100,
totalCommits: 200,
totalIssues: 300,
totalPRs: 400,
totalPRsMerged: 320,
mergedPRsPercentage: 80,
totalReviews: 50,
totalDiscussionsStarted: 10,
totalDiscussionsAnswered: 50,
contributedTo: 500,
rank: { level: "A+", percentile: 40 },
};
describe("Test renderStatsCard", () => {
it("should render correctly", () => {
document.body.innerHTML = renderStatsCard(stats);
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"Anurag Hazra's GitHub Stats",
);
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("height"),
).toBe("195");
expect(getByTestId(document.body, "stars").textContent).toBe("100");
expect(getByTestId(document.body, "commits").textContent).toBe("200");
expect(getByTestId(document.body, "issues").textContent).toBe("300");
expect(getByTestId(document.body, "prs").textContent).toBe("400");
expect(getByTestId(document.body, "contribs").textContent).toBe("500");
expect(queryByTestId(document.body, "card-bg")).toBeInTheDocument();
expect(queryByTestId(document.body, "rank-circle")).toBeInTheDocument();
// Default hidden stats
expect(queryByTestId(document.body, "reviews")).not.toBeInTheDocument();
expect(
queryByTestId(document.body, "discussions_started"),
).not.toBeInTheDocument();
expect(
queryByTestId(document.body, "discussions_answered"),
).not.toBeInTheDocument();
expect(queryByTestId(document.body, "prs_merged")).not.toBeInTheDocument();
expect(
queryByTestId(document.body, "prs_merged_percentage"),
).not.toBeInTheDocument();
});
it("should have proper name apostrophe", () => {
document.body.innerHTML = renderStatsCard({ ...stats, name: "Anil Das" });
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"Anil Das' GitHub Stats",
);
document.body.innerHTML = renderStatsCard({ ...stats, name: "Felix" });
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"Felix's GitHub Stats",
);
});
it("should hide individual stats", () => {
document.body.innerHTML = renderStatsCard(stats, {
hide: ["issues", "prs", "contribs"],
});
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("height"),
).toBe("150"); // height should be 150 because we clamped it.
expect(queryByTestId(document.body, "stars")).toBeDefined();
expect(queryByTestId(document.body, "commits")).toBeDefined();
expect(queryByTestId(document.body, "issues")).toBeNull();
expect(queryByTestId(document.body, "prs")).toBeNull();
expect(queryByTestId(document.body, "contribs")).toBeNull();
expect(queryByTestId(document.body, "reviews")).toBeNull();
expect(queryByTestId(document.body, "discussions_started")).toBeNull();
expect(queryByTestId(document.body, "discussions_answered")).toBeNull();
expect(queryByTestId(document.body, "prs_merged")).toBeNull();
expect(queryByTestId(document.body, "prs_merged_percentage")).toBeNull();
});
it("should show additional stats", () => {
document.body.innerHTML = renderStatsCard(stats, {
show: [
"reviews",
"discussions_started",
"discussions_answered",
"prs_merged",
"prs_merged_percentage",
],
});
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("height"),
).toBe("320");
expect(queryByTestId(document.body, "stars")).toBeDefined();
expect(queryByTestId(document.body, "commits")).toBeDefined();
expect(queryByTestId(document.body, "issues")).toBeDefined();
expect(queryByTestId(document.body, "prs")).toBeDefined();
expect(queryByTestId(document.body, "contribs")).toBeDefined();
expect(queryByTestId(document.body, "reviews")).toBeDefined();
expect(queryByTestId(document.body, "discussions_started")).toBeDefined();
expect(queryByTestId(document.body, "discussions_answered")).toBeDefined();
expect(queryByTestId(document.body, "prs_merged")).toBeDefined();
expect(queryByTestId(document.body, "prs_merged_percentage")).toBeDefined();
});
it("should hide_rank", () => {
document.body.innerHTML = renderStatsCard(stats, { hide_rank: true });
expect(queryByTestId(document.body, "rank-circle")).not.toBeInTheDocument();
});
it("should render with custom width set", () => {
document.body.innerHTML = renderStatsCard(stats);
expect(document.querySelector("svg")).toHaveAttribute("width", "450");
document.body.innerHTML = renderStatsCard(stats, { card_width: 500 });
expect(document.querySelector("svg")).toHaveAttribute("width", "500");
});
it("should render with custom width set and limit minimum width", () => {
document.body.innerHTML = renderStatsCard(stats, { card_width: 1 });
expect(document.querySelector("svg")).toHaveAttribute("width", "420");
// Test default minimum card width without rank circle.
document.body.innerHTML = renderStatsCard(stats, {
card_width: 1,
hide_rank: true,
});
expect(document.querySelector("svg")).toHaveAttribute(
"width",
"305.81250000000006",
);
// Test minimum card width with rank and icons.
document.body.innerHTML = renderStatsCard(stats, {
card_width: 1,
hide_rank: true,
show_icons: true,
});
expect(document.querySelector("svg")).toHaveAttribute(
"width",
"322.81250000000006",
);
// Test minimum card width with icons but without rank.
document.body.innerHTML = renderStatsCard(stats, {
card_width: 1,
hide_rank: false,
show_icons: true,
});
expect(document.querySelector("svg")).toHaveAttribute("width", "437");
// Test minimum card width without icons or rank.
document.body.innerHTML = renderStatsCard(stats, {
card_width: 1,
hide_rank: false,
show_icons: false,
});
expect(document.querySelector("svg")).toHaveAttribute("width", "420");
});
it("should render default colors properly", () => {
document.body.innerHTML = renderStatsCard(stats);
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.textContent);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe("#2f80ed");
expect(statClassStyles.fill.trim()).toBe("#434d58");
expect(iconClassStyles.fill.trim()).toBe("#4c71f2");
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#fffefe",
);
});
it("should render custom colors properly", () => {
const customColors = {
title_color: "5a0",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderStatsCard(stats, { ...customColors });
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(statClassStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${customColors.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render custom colors with themes", () => {
document.body.innerHTML = renderStatsCard(stats, {
title_color: "5a0",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe("#5a0");
expect(statClassStyles.fill.trim()).toBe(`#${themes.radical.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should render with all the themes", () => {
Object.keys(themes).forEach((name) => {
document.body.innerHTML = renderStatsCard(stats, {
theme: name,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes[name].title_color}`,
);
expect(statClassStyles.fill.trim()).toBe(`#${themes[name].text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes[name].icon_color}`);
const backgroundElement = queryByTestId(document.body, "card-bg");
const backgroundElementFill = backgroundElement.getAttribute("fill");
expect([`#${themes[name].bg_color}`, "url(#gradient)"]).toContain(
backgroundElementFill,
);
});
});
it("should render custom colors with themes and fallback to default colors if invalid", () => {
document.body.innerHTML = renderStatsCard(stats, {
title_color: "invalid color",
text_color: "invalid color",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes.default.title_color}`,
);
expect(statClassStyles.fill.trim()).toBe(`#${themes.default.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should render custom ring_color properly", () => {
const customColors = {
title_color: "5a0",
ring_color: "0000ff",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderStatsCard(stats, { ...customColors });
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
const rankCircleStyles = stylesObject[":host"][".rank-circle "];
const rankCircleRimStyles = stylesObject[":host"][".rank-circle-rim "];
expect(headerClassStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(statClassStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${customColors.icon_color}`);
expect(rankCircleStyles.stroke.trim()).toBe(`#${customColors.ring_color}`);
expect(rankCircleRimStyles.stroke.trim()).toBe(
`#${customColors.ring_color}`,
);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render icons correctly", () => {
document.body.innerHTML = renderStatsCard(stats, {
show_icons: true,
});
expect(queryAllByTestId(document.body, "icon")[0]).toBeDefined();
expect(queryByTestId(document.body, "stars")).toBeDefined();
expect(
queryByTestId(document.body, "stars").previousElementSibling, // the label
).toHaveAttribute("x", "25");
});
it("should not have icons if show_icons is false", () => {
document.body.innerHTML = renderStatsCard(stats, { show_icons: false });
expect(queryAllByTestId(document.body, "icon")[0]).not.toBeDefined();
expect(queryByTestId(document.body, "stars")).toBeDefined();
expect(
queryByTestId(document.body, "stars").previousElementSibling, // the label
).not.toHaveAttribute("x");
});
it("should auto resize if hide_rank is true", () => {
document.body.innerHTML = renderStatsCard(stats, {
hide_rank: true,
});
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("width"),
).toBe("305.81250000000006");
});
it("should auto resize if hide_rank is true & custom_title is set", () => {
document.body.innerHTML = renderStatsCard(stats, {
hide_rank: true,
custom_title: "Hello world",
});
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("width"),
).toBe("287");
});
it("should render translations", () => {
document.body.innerHTML = renderStatsCard(stats, { locale: "cn" });
expect(document.getElementsByClassName("header")[0].textContent).toBe(
"Anurag Hazra 的 GitHub 统计数据",
);
expect(
document.querySelector(
'g[transform="translate(0, 0)"]>.stagger>.stat.bold',
).textContent,
).toMatchInlineSnapshot(`"获标星数:"`);
expect(
document.querySelector(
'g[transform="translate(0, 25)"]>.stagger>.stat.bold',
).textContent,
).toMatchInlineSnapshot(`"累计提交总数 (去年):"`);
expect(
document.querySelector(
'g[transform="translate(0, 50)"]>.stagger>.stat.bold',
).textContent,
).toMatchInlineSnapshot(`"发起的 PR 总数:"`);
expect(
document.querySelector(
'g[transform="translate(0, 75)"]>.stagger>.stat.bold',
).textContent,
).toMatchInlineSnapshot(`"提出的 issue 总数:"`);
expect(
document.querySelector(
'g[transform="translate(0, 100)"]>.stagger>.stat.bold',
).textContent,
).toMatchInlineSnapshot(`"贡献的项目数(去年):"`);
});
it("should render without rounding", () => {
document.body.innerHTML = renderStatsCard(stats, { border_radius: "0" });
expect(document.querySelector("rect")).toHaveAttribute("rx", "0");
document.body.innerHTML = renderStatsCard(stats, {});
expect(document.querySelector("rect")).toHaveAttribute("rx", "4.5");
});
it("should shorten values", () => {
stats["totalCommits"] = 1999;
document.body.innerHTML = renderStatsCard(stats);
expect(getByTestId(document.body, "commits").textContent).toBe("2k");
document.body.innerHTML = renderStatsCard(stats, { number_format: "long" });
expect(getByTestId(document.body, "commits").textContent).toBe("1999");
document.body.innerHTML = renderStatsCard(stats, { number_precision: 2 });
expect(getByTestId(document.body, "commits").textContent).toBe("2.00k");
document.body.innerHTML = renderStatsCard(stats, {
number_format: "long",
number_precision: 2,
});
expect(getByTestId(document.body, "commits").textContent).toBe("1999");
});
it("should render default rank icon with level A+", () => {
document.body.innerHTML = renderStatsCard(stats, {
rank_icon: "default",
});
expect(queryByTestId(document.body, "level-rank-icon")).toBeDefined();
expect(
queryByTestId(document.body, "level-rank-icon").textContent.trim(),
).toBe("A+");
});
it("should render github rank icon", () => {
document.body.innerHTML = renderStatsCard(stats, {
rank_icon: "github",
});
expect(queryByTestId(document.body, "github-rank-icon")).toBeDefined();
});
it("should show the rank percentile", () => {
document.body.innerHTML = renderStatsCard(stats, {
rank_icon: "percentile",
});
expect(queryByTestId(document.body, "percentile-top-header")).toBeDefined();
expect(
queryByTestId(document.body, "percentile-top-header").textContent.trim(),
).toBe("Top");
expect(queryByTestId(document.body, "rank-percentile-text")).toBeDefined();
expect(
queryByTestId(document.body, "percentile-rank-value").textContent.trim(),
).toBe(stats.rank.percentile.toFixed(1) + "%");
});
it("should throw error if all stats and rank icon are hidden", () => {
expect(() =>
renderStatsCard(stats, {
hide: ["stars", "commits", "prs", "issues", "contribs"],
hide_rank: true,
}),
).toThrow(
new CustomError(
"Could not render stats card.",
"Either stats or rank are required.",
),
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/color.test.js | tests/color.test.js | import { getCardColors } from "../src/common/color";
import { describe, expect, it } from "@jest/globals";
describe("Test color.js", () => {
it("getCardColors: should return expected values", () => {
let colors = getCardColors({
title_color: "f00",
text_color: "0f0",
ring_color: "0000ff",
icon_color: "00f",
bg_color: "fff",
border_color: "fff",
theme: "dark",
});
expect(colors).toStrictEqual({
titleColor: "#f00",
textColor: "#0f0",
iconColor: "#00f",
ringColor: "#0000ff",
bgColor: "#fff",
borderColor: "#fff",
});
});
it("getCardColors: should fallback to default colors if color is invalid", () => {
let colors = getCardColors({
title_color: "invalidcolor",
text_color: "0f0",
icon_color: "00f",
bg_color: "fff",
border_color: "invalidColor",
theme: "dark",
});
expect(colors).toStrictEqual({
titleColor: "#2f80ed",
textColor: "#0f0",
iconColor: "#00f",
ringColor: "#2f80ed",
bgColor: "#fff",
borderColor: "#e4e2e2",
});
});
it("getCardColors: should fallback to specified theme colors if is not defined", () => {
let colors = getCardColors({
theme: "dark",
});
expect(colors).toStrictEqual({
titleColor: "#fff",
textColor: "#9f9f9f",
ringColor: "#fff",
iconColor: "#79ff97",
bgColor: "#151515",
borderColor: "#e4e2e2",
});
});
it("getCardColors: should return ring color equal to title color if not ring color is defined", () => {
let colors = getCardColors({
title_color: "f00",
text_color: "0f0",
icon_color: "00f",
bg_color: "fff",
border_color: "fff",
theme: "dark",
});
expect(colors).toStrictEqual({
titleColor: "#f00",
textColor: "#0f0",
iconColor: "#00f",
ringColor: "#f00",
bgColor: "#fff",
borderColor: "#fff",
});
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/gist.test.js | tests/gist.test.js | // @ts-check
import { afterEach, describe, expect, it, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import gist from "../api/gist.js";
import { renderGistCard } from "../src/cards/gist.js";
import { renderError } from "../src/common/render.js";
import { CACHE_TTL, DURATIONS } from "../src/common/cache.js";
const gist_data = {
data: {
viewer: {
gist: {
description:
"List of countries and territories in English and Spanish: name, continent, capital, dial code, country codes, TLD, and area in sq km. Lista de países y territorios en Inglés y Español: nombre, continente, capital, código de teléfono, códigos de país, dominio y área en km cuadrados. Updated 2023",
owner: {
login: "Yizack",
},
stargazerCount: 33,
forks: {
totalCount: 11,
},
files: [
{
name: "countries.json",
language: {
name: "JSON",
},
size: 85858,
},
],
},
},
},
};
const gist_not_found_data = {
data: {
viewer: {
gist: null,
},
},
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test /api/gist", () => {
it("should test the request", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, gist_data);
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderGistCard({
name: gist_data.data.viewer.gist.files[0].name,
nameWithOwner: `${gist_data.data.viewer.gist.owner.login}/${gist_data.data.viewer.gist.files[0].name}`,
description: gist_data.data.viewer.gist.description,
language: gist_data.data.viewer.gist.files[0].language.name,
starsCount: gist_data.data.viewer.gist.stargazerCount,
forksCount: gist_data.data.viewer.gist.forks.totalCount,
}),
);
});
it("should get the query options", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
show_owner: true,
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, gist_data);
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderGistCard(
{
name: gist_data.data.viewer.gist.files[0].name,
nameWithOwner: `${gist_data.data.viewer.gist.owner.login}/${gist_data.data.viewer.gist.files[0].name}`,
description: gist_data.data.viewer.gist.description,
language: gist_data.data.viewer.gist.files[0].language.name,
starsCount: gist_data.data.viewer.gist.stargazerCount,
forksCount: gist_data.data.viewer.gist.forks.totalCount,
},
{ ...req.query },
),
);
});
it("should render error if id is not provided", async () => {
const req = {
query: {},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: 'Missing params "id" make sure you pass the parameters in URL',
secondaryMessage: "/api/gist?id=GIST_ID",
renderOptions: { show_repo_link: false },
}),
);
});
it("should render error if gist is not found", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock
.onPost("https://api.github.com/graphql")
.reply(200, gist_not_found_data);
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({ message: "Gist not found" }),
);
});
it("should render error if wrong locale is provided", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
locale: "asdf",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
}),
);
});
it("should have proper cache", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").reply(200, gist_data);
await gist(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.setHeader).toHaveBeenCalledWith(
"Cache-Control",
`max-age=${CACHE_TTL.GIST_CARD.DEFAULT}, ` +
`s-maxage=${CACHE_TTL.GIST_CARD.DEFAULT}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/i18n.test.js | tests/i18n.test.js | import { describe, expect, it } from "@jest/globals";
import { I18n } from "../src/common/I18n.js";
import { statCardLocales } from "../src/translations.js";
describe("I18n", () => {
it("should return translated string", () => {
const i18n = new I18n({
locale: "en",
translations: statCardLocales({ name: "Anurag Hazra", apostrophe: "s" }),
});
expect(i18n.t("statcard.title")).toBe("Anurag Hazra's GitHub Stats");
});
it("should throw error if translation string not found", () => {
const i18n = new I18n({
locale: "en",
translations: statCardLocales({ name: "Anurag Hazra", apostrophe: "s" }),
});
expect(() => i18n.t("statcard.title1")).toThrow(
"statcard.title1 Translation string not found",
);
});
it("should throw error if translation not found for locale", () => {
const i18n = new I18n({
locale: "asdf",
translations: statCardLocales({ name: "Anurag Hazra", apostrophe: "s" }),
});
expect(() => i18n.t("statcard.title")).toThrow(
"'statcard.title' translation not found for locale 'asdf'",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/renderGistCard.test.js | tests/renderGistCard.test.js | import { describe, expect, it } from "@jest/globals";
import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom";
import { cssToObject } from "@uppercod/css-to-object";
import { renderGistCard } from "../src/cards/gist.js";
import { themes } from "../themes/index.js";
/**
* @type {import("../src/fetchers/gist").GistData}
*/
const data = {
name: "test",
nameWithOwner: "anuraghazra/test",
description: "Small test repository with different Python programs.",
language: "Python",
starsCount: 163,
forksCount: 19,
};
describe("test renderGistCard", () => {
it("should render correctly", () => {
document.body.innerHTML = renderGistCard(data);
const [header] = document.getElementsByClassName("header");
expect(header).toHaveTextContent("test");
expect(header).not.toHaveTextContent("anuraghazra");
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"Small test repository with different Python programs.",
);
expect(queryByTestId(document.body, "starsCount")).toHaveTextContent("163");
expect(queryByTestId(document.body, "forksCount")).toHaveTextContent("19");
expect(queryByTestId(document.body, "lang-name")).toHaveTextContent(
"Python",
);
expect(queryByTestId(document.body, "lang-color")).toHaveAttribute(
"fill",
"#3572A5",
);
});
it("should display username in title if show_owner is true", () => {
document.body.innerHTML = renderGistCard(data, { show_owner: true });
const [header] = document.getElementsByClassName("header");
expect(header).toHaveTextContent("anuraghazra/test");
});
it("should trim header if name is too long", () => {
document.body.innerHTML = renderGistCard({
...data,
name: "some-really-long-repo-name-for-test-purposes",
});
const [header] = document.getElementsByClassName("header");
expect(header).toHaveTextContent("some-really-long-repo-name-for-test...");
});
it("should trim description if description os too long", () => {
document.body.innerHTML = renderGistCard({
...data,
description:
"The quick brown fox jumps over the lazy dog is an English-language pangram—a sentence that contains all of the letters of the English alphabet",
});
expect(
document.getElementsByClassName("description")[0].children[0].textContent,
).toBe("The quick brown fox jumps over the lazy dog is an");
expect(
document.getElementsByClassName("description")[0].children[1].textContent,
).toBe("English-language pangram—a sentence that contains all");
});
it("should not trim description if it is short", () => {
document.body.innerHTML = renderGistCard({
...data,
description: "Small text should not trim",
});
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"Small text should not trim",
);
});
it("should render emojis in description", () => {
document.body.innerHTML = renderGistCard({
...data,
description: "This is a test gist description with :heart: emoji.",
});
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"This is a test gist description with ❤️ emoji.",
);
});
it("should render custom colors properly", () => {
const customColors = {
title_color: "5a0",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderGistCard(data, {
...customColors,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(descClassStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${customColors.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render with all the themes", () => {
Object.keys(themes).forEach((name) => {
document.body.innerHTML = renderGistCard(data, {
theme: name,
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes[name].title_color}`,
);
expect(descClassStyles.fill.trim()).toBe(`#${themes[name].text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes[name].icon_color}`);
const backgroundElement = queryByTestId(document.body, "card-bg");
const backgroundElementFill = backgroundElement.getAttribute("fill");
expect([`#${themes[name].bg_color}`, "url(#gradient)"]).toContain(
backgroundElementFill,
);
});
});
it("should render custom colors with themes", () => {
document.body.innerHTML = renderGistCard(data, {
title_color: "5a0",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe("#5a0");
expect(descClassStyles.fill.trim()).toBe(`#${themes.radical.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should render custom colors with themes and fallback to default colors if invalid", () => {
document.body.innerHTML = renderGistCard(data, {
title_color: "invalid color",
text_color: "invalid color",
theme: "radical",
});
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const descClassStyles = stylesObject[":host"][".description "];
const iconClassStyles = stylesObject[":host"][".icon "];
expect(headerClassStyles.fill.trim()).toBe(
`#${themes.default.title_color}`,
);
expect(descClassStyles.fill.trim()).toBe(`#${themes.default.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${themes.radical.icon_color}`);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
`#${themes.radical.bg_color}`,
);
});
it("should not render star count or fork count if either of the are zero", () => {
document.body.innerHTML = renderGistCard({
...data,
starsCount: 0,
});
expect(queryByTestId(document.body, "starsCount")).toBeNull();
expect(queryByTestId(document.body, "forksCount")).toBeInTheDocument();
document.body.innerHTML = renderGistCard({
...data,
starsCount: 1,
forksCount: 0,
});
expect(queryByTestId(document.body, "starsCount")).toBeInTheDocument();
expect(queryByTestId(document.body, "forksCount")).toBeNull();
document.body.innerHTML = renderGistCard({
...data,
starsCount: 0,
forksCount: 0,
});
expect(queryByTestId(document.body, "starsCount")).toBeNull();
expect(queryByTestId(document.body, "forksCount")).toBeNull();
});
it("should render without rounding", () => {
document.body.innerHTML = renderGistCard(data, {
border_radius: "0",
});
expect(document.querySelector("rect")).toHaveAttribute("rx", "0");
document.body.innerHTML = renderGistCard(data, {});
expect(document.querySelector("rect")).toHaveAttribute("rx", "4.5");
});
it("should fallback to default description", () => {
document.body.innerHTML = renderGistCard({
...data,
description: undefined,
});
expect(document.getElementsByClassName("description")[0]).toHaveTextContent(
"No description provided",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fetchTopLanguages.test.js | tests/fetchTopLanguages.test.js | import { afterEach, describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { fetchTopLanguages } from "../src/fetchers/top-languages.js";
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
const data_langs = {
data: {
user: {
repositories: {
nodes: [
{
name: "test-repo-1",
languages: {
edges: [{ size: 100, node: { color: "#0f0", name: "HTML" } }],
},
},
{
name: "test-repo-2",
languages: {
edges: [{ size: 100, node: { color: "#0f0", name: "HTML" } }],
},
},
{
name: "test-repo-3",
languages: {
edges: [
{ size: 100, node: { color: "#0ff", name: "javascript" } },
],
},
},
{
name: "test-repo-4",
languages: {
edges: [
{ size: 100, node: { color: "#0ff", name: "javascript" } },
],
},
},
],
},
},
},
};
const error = {
errors: [
{
type: "NOT_FOUND",
path: ["user"],
locations: [],
message: "Could not resolve to a User with the login of 'noname'.",
},
],
};
describe("FetchTopLanguages", () => {
it("should fetch correct language data while using the new calculation", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
let repo = await fetchTopLanguages("anuraghazra", [], 0.5, 0.5);
expect(repo).toStrictEqual({
HTML: {
color: "#0f0",
count: 2,
name: "HTML",
size: 20.000000000000004,
},
javascript: {
color: "#0ff",
count: 2,
name: "javascript",
size: 20.000000000000004,
},
});
});
it("should fetch correct language data while excluding the 'test-repo-1' repository", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
let repo = await fetchTopLanguages("anuraghazra", ["test-repo-1"]);
expect(repo).toStrictEqual({
HTML: {
color: "#0f0",
count: 1,
name: "HTML",
size: 100,
},
javascript: {
color: "#0ff",
count: 2,
name: "javascript",
size: 200,
},
});
});
it("should fetch correct language data while using the old calculation", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
let repo = await fetchTopLanguages("anuraghazra", [], 1, 0);
expect(repo).toStrictEqual({
HTML: {
color: "#0f0",
count: 2,
name: "HTML",
size: 200,
},
javascript: {
color: "#0ff",
count: 2,
name: "javascript",
size: 200,
},
});
});
it("should rank languages by the number of repositories they appear in", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_langs);
let repo = await fetchTopLanguages("anuraghazra", [], 0, 1);
expect(repo).toStrictEqual({
HTML: {
color: "#0f0",
count: 2,
name: "HTML",
size: 2,
},
javascript: {
color: "#0ff",
count: 2,
name: "javascript",
size: 2,
},
});
});
it("should throw specific error when user not found", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, error);
await expect(fetchTopLanguages("anuraghazra")).rejects.toThrow(
"Could not resolve to a User with the login of 'noname'.",
);
});
it("should throw other errors with their message", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, {
errors: [{ message: "Some test GraphQL error" }],
});
await expect(fetchTopLanguages("anuraghazra")).rejects.toThrow(
"Some test GraphQL error",
);
});
it("should throw error with specific message when error does not contain message property", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, {
errors: [{ type: "TEST" }],
});
await expect(fetchTopLanguages("anuraghazra")).rejects.toThrow(
"Something went wrong while trying to retrieve the language data using the GraphQL API.",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fetchRepo.test.js | tests/fetchRepo.test.js | import { afterEach, describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { fetchRepo } from "../src/fetchers/repo.js";
const data_repo = {
repository: {
name: "convoychat",
stargazers: { totalCount: 38000 },
description: "Help us take over the world! React + TS + GraphQL Chat App",
primaryLanguage: {
color: "#2b7489",
id: "MDg6TGFuZ3VhZ2UyODc=",
name: "TypeScript",
},
forkCount: 100,
},
};
const data_user = {
data: {
user: { repository: data_repo.repository },
organization: null,
},
};
const data_org = {
data: {
user: null,
organization: { repository: data_repo.repository },
},
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test fetchRepo", () => {
it("should fetch correct user repo", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
let repo = await fetchRepo("anuraghazra", "convoychat");
expect(repo).toStrictEqual({
...data_repo.repository,
starCount: data_repo.repository.stargazers.totalCount,
});
});
it("should fetch correct org repo", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, data_org);
let repo = await fetchRepo("anuraghazra", "convoychat");
expect(repo).toStrictEqual({
...data_repo.repository,
starCount: data_repo.repository.stargazers.totalCount,
});
});
it("should throw error if user is found but repo is null", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(200, { data: { user: { repository: null }, organization: null } });
await expect(fetchRepo("anuraghazra", "convoychat")).rejects.toThrow(
"User Repository Not found",
);
});
it("should throw error if org is found but repo is null", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(200, { data: { user: null, organization: { repository: null } } });
await expect(fetchRepo("anuraghazra", "convoychat")).rejects.toThrow(
"Organization Repository Not found",
);
});
it("should throw error if both user & org data not found", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(200, { data: { user: null, organization: null } });
await expect(fetchRepo("anuraghazra", "convoychat")).rejects.toThrow(
"Not found",
);
});
it("should throw error if repository is private", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, {
data: {
user: { repository: { ...data_repo, isPrivate: true } },
organization: null,
},
});
await expect(fetchRepo("anuraghazra", "convoychat")).rejects.toThrow(
"User Repository Not found",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fmt.test.js | tests/fmt.test.js | import { describe, expect, it } from "@jest/globals";
import {
formatBytes,
kFormatter,
wrapTextMultiline,
} from "../src/common/fmt.js";
describe("Test fmt.js", () => {
it("kFormatter: should format numbers correctly by default", () => {
expect(kFormatter(1)).toBe(1);
expect(kFormatter(-1)).toBe(-1);
expect(kFormatter(500)).toBe(500);
expect(kFormatter(1000)).toBe("1k");
expect(kFormatter(1200)).toBe("1.2k");
expect(kFormatter(10000)).toBe("10k");
expect(kFormatter(12345)).toBe("12.3k");
expect(kFormatter(99900)).toBe("99.9k");
expect(kFormatter(9900000)).toBe("9900k");
});
it("kFormatter: should format numbers correctly with 0 decimal precision", () => {
expect(kFormatter(1, 0)).toBe("0k");
expect(kFormatter(-1, 0)).toBe("-0k");
expect(kFormatter(500, 0)).toBe("1k");
expect(kFormatter(1000, 0)).toBe("1k");
expect(kFormatter(1200, 0)).toBe("1k");
expect(kFormatter(10000, 0)).toBe("10k");
expect(kFormatter(12345, 0)).toBe("12k");
expect(kFormatter(99000, 0)).toBe("99k");
expect(kFormatter(99900, 0)).toBe("100k");
expect(kFormatter(9900000, 0)).toBe("9900k");
});
it("kFormatter: should format numbers correctly with 1 decimal precision", () => {
expect(kFormatter(1, 1)).toBe("0.0k");
expect(kFormatter(-1, 1)).toBe("-0.0k");
expect(kFormatter(500, 1)).toBe("0.5k");
expect(kFormatter(1000, 1)).toBe("1.0k");
expect(kFormatter(1200, 1)).toBe("1.2k");
expect(kFormatter(10000, 1)).toBe("10.0k");
expect(kFormatter(12345, 1)).toBe("12.3k");
expect(kFormatter(99900, 1)).toBe("99.9k");
expect(kFormatter(9900000, 1)).toBe("9900.0k");
});
it("kFormatter: should format numbers correctly with 2 decimal precision", () => {
expect(kFormatter(1, 2)).toBe("0.00k");
expect(kFormatter(-1, 2)).toBe("-0.00k");
expect(kFormatter(500, 2)).toBe("0.50k");
expect(kFormatter(1000, 2)).toBe("1.00k");
expect(kFormatter(1200, 2)).toBe("1.20k");
expect(kFormatter(10000, 2)).toBe("10.00k");
expect(kFormatter(12345, 2)).toBe("12.35k");
expect(kFormatter(99900, 2)).toBe("99.90k");
expect(kFormatter(9900000, 2)).toBe("9900.00k");
});
it("formatBytes: should return expected values", () => {
expect(formatBytes(0)).toBe("0 B");
expect(formatBytes(100)).toBe("100.0 B");
expect(formatBytes(1024)).toBe("1.0 KB");
expect(formatBytes(1024 * 1024)).toBe("1.0 MB");
expect(formatBytes(1024 * 1024 * 1024)).toBe("1.0 GB");
expect(formatBytes(1024 * 1024 * 1024 * 1024)).toBe("1.0 TB");
expect(formatBytes(1024 * 1024 * 1024 * 1024 * 1024)).toBe("1.0 PB");
expect(formatBytes(1024 * 1024 * 1024 * 1024 * 1024 * 1024)).toBe("1.0 EB");
expect(formatBytes(1234 * 1024)).toBe("1.2 MB");
expect(formatBytes(123.4 * 1024)).toBe("123.4 KB");
});
it("wrapTextMultiline: should not wrap small texts", () => {
{
let multiLineText = wrapTextMultiline("Small text should not wrap");
expect(multiLineText).toEqual(["Small text should not wrap"]);
}
});
it("wrapTextMultiline: should wrap large texts", () => {
let multiLineText = wrapTextMultiline(
"Hello world long long long text",
20,
3,
);
expect(multiLineText).toEqual(["Hello world long", "long long text"]);
});
it("wrapTextMultiline: should wrap large texts and limit max lines", () => {
let multiLineText = wrapTextMultiline(
"Hello world long long long text",
10,
2,
);
expect(multiLineText).toEqual(["Hello", "world long..."]);
});
it("wrapTextMultiline: should wrap chinese by punctuation", () => {
let multiLineText = wrapTextMultiline(
"专门为刚开始刷题的同学准备的算法基地,没有最细只有更细,立志用动画将晦涩难懂的算法说的通俗易懂!",
);
expect(multiLineText.length).toEqual(3);
expect(multiLineText[0].length).toEqual(18 * 8); // &#xxxxx; x 8
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/api.test.js | tests/api.test.js | // @ts-check
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import api from "../api/index.js";
import { calculateRank } from "../src/calculateRank.js";
import { renderStatsCard } from "../src/cards/stats.js";
import { renderError } from "../src/common/render.js";
import { CACHE_TTL, DURATIONS } from "../src/common/cache.js";
/**
* @type {import("../src/fetchers/stats").StatsData}
*/
const stats = {
name: "Anurag Hazra",
totalStars: 100,
totalCommits: 200,
totalIssues: 300,
totalPRs: 400,
totalPRsMerged: 320,
mergedPRsPercentage: 80,
totalReviews: 50,
totalDiscussionsStarted: 10,
totalDiscussionsAnswered: 40,
contributedTo: 50,
rank: { level: "DEV", percentile: 0 },
};
stats.rank = calculateRank({
all_commits: false,
commits: stats.totalCommits,
prs: stats.totalPRs,
reviews: stats.totalReviews,
issues: stats.totalIssues,
repos: 1,
stars: stats.totalStars,
followers: 0,
});
const data_stats = {
data: {
user: {
name: stats.name,
repositoriesContributedTo: { totalCount: stats.contributedTo },
commits: {
totalCommitContributions: stats.totalCommits,
},
reviews: {
totalPullRequestReviewContributions: stats.totalReviews,
},
pullRequests: { totalCount: stats.totalPRs },
mergedPullRequests: { totalCount: stats.totalPRsMerged },
openIssues: { totalCount: stats.totalIssues },
closedIssues: { totalCount: 0 },
followers: { totalCount: 0 },
repositoryDiscussions: { totalCount: stats.totalDiscussionsStarted },
repositoryDiscussionComments: {
totalCount: stats.totalDiscussionsAnswered,
},
repositories: {
totalCount: 1,
nodes: [{ stargazers: { totalCount: 100 } }],
pageInfo: {
hasNextPage: false,
endCursor: "cursor",
},
},
},
},
};
const error = {
errors: [
{
type: "NOT_FOUND",
path: ["user"],
locations: [],
message: "Could not fetch user",
},
],
};
const mock = new MockAdapter(axios);
// @ts-ignore
const faker = (query, data) => {
const req = {
query: {
username: "anuraghazra",
...query,
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").replyOnce(200, data);
return { req, res };
};
beforeEach(() => {
process.env.CACHE_SECONDS = undefined;
});
afterEach(() => {
mock.reset();
});
describe("Test /api/", () => {
it("should test the request", async () => {
const { req, res } = faker({}, data_stats);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderStatsCard(stats, { ...req.query }),
);
});
it("should render error card on error", async () => {
const { req, res } = faker({}, error);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: error.errors[0].message,
secondaryMessage:
"Make sure the provided username is not an organization",
}),
);
});
it("should render error card in same theme as requested card", async () => {
const { req, res } = faker({ theme: "merko" }, error);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: error.errors[0].message,
secondaryMessage:
"Make sure the provided username is not an organization",
renderOptions: { theme: "merko" },
}),
);
});
it("should get the query options", async () => {
const { req, res } = faker(
{
username: "anuraghazra",
hide: "issues,prs,contribs",
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
},
data_stats,
);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderStatsCard(stats, {
hide: ["issues", "prs", "contribs"],
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
}),
);
});
it("should have proper cache", async () => {
const { req, res } = faker({}, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${CACHE_TTL.STATS_CARD.DEFAULT}, ` +
`s-maxage=${CACHE_TTL.STATS_CARD.DEFAULT}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
});
it("should set proper cache", async () => {
const cache_seconds = DURATIONS.TWELVE_HOURS;
const { req, res } = faker({ cache_seconds }, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${cache_seconds}, ` +
`s-maxage=${cache_seconds}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
});
it("should set shorter cache when error", async () => {
const { req, res } = faker({}, error);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${CACHE_TTL.ERROR}, ` +
`s-maxage=${CACHE_TTL.ERROR}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
});
it("should properly set cache using CACHE_SECONDS env variable", async () => {
const cacheSeconds = "10000";
process.env.CACHE_SECONDS = cacheSeconds;
const { req, res } = faker({}, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${cacheSeconds}, ` +
`s-maxage=${cacheSeconds}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
});
it("should disable cache when CACHE_SECONDS is set to 0", async () => {
process.env.CACHE_SECONDS = "0";
const { req, res } = faker({}, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
"no-cache, no-store, must-revalidate, max-age=0, s-maxage=0",
],
["Pragma", "no-cache"],
["Expires", "0"],
]);
});
it("should set proper cache with clamped values", async () => {
{
let { req, res } = faker({ cache_seconds: 200_000 }, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${CACHE_TTL.STATS_CARD.MAX}, ` +
`s-maxage=${CACHE_TTL.STATS_CARD.MAX}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
}
// note i'm using block scoped vars
{
let { req, res } = faker({ cache_seconds: 0 }, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${CACHE_TTL.STATS_CARD.MIN}, ` +
`s-maxage=${CACHE_TTL.STATS_CARD.MIN}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
}
{
let { req, res } = faker({ cache_seconds: -10_000 }, data_stats);
await api(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"],
[
"Cache-Control",
`max-age=${CACHE_TTL.STATS_CARD.MIN}, ` +
`s-maxage=${CACHE_TTL.STATS_CARD.MIN}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
],
]);
}
});
it("should allow changing ring_color", async () => {
const { req, res } = faker(
{
username: "anuraghazra",
hide: "issues,prs,contribs",
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
ring_color: "0000ff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
},
data_stats,
);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderStatsCard(stats, {
hide: ["issues", "prs", "contribs"],
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
ring_color: "0000ff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
}),
);
});
it("should render error card if username in blacklist", async () => {
const { req, res } = faker({ username: "renovate-bot" }, data_stats);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "This username is blacklisted",
secondaryMessage: "Please deploy your own instance",
renderOptions: { show_repo_link: false },
}),
);
});
it("should render error card when wrong locale is provided", async () => {
const { req, res } = faker({ locale: "asdf" }, data_stats);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
}),
);
});
it("should render error card when include_all_commits true and upstream API fails", async () => {
mock
.onGet("https://api.github.com/search/commits?q=author:anuraghazra")
.reply(200, { error: "Some test error message" });
const { req, res } = faker(
{ username: "anuraghazra", include_all_commits: true },
data_stats,
);
await api(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderError({
message: "Could not fetch total commits.",
secondaryMessage: "Please try again later",
}),
);
// Received SVG output should not contain string "https://tiny.one/readme-stats"
expect(res.send.mock.calls[0][0]).not.toContain(
"https://tiny.one/readme-stats",
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/flexLayout.test.js | tests/flexLayout.test.js | import { describe, expect, it } from "@jest/globals";
import { flexLayout } from "../src/common/render.js";
describe("flexLayout", () => {
it("should work with row & col layouts", () => {
const layout = flexLayout({
items: ["<text>1</text>", "<text>2</text>"],
gap: 60,
});
expect(layout).toStrictEqual([
`<g transform="translate(0, 0)"><text>1</text></g>`,
`<g transform="translate(60, 0)"><text>2</text></g>`,
]);
const columns = flexLayout({
items: ["<text>1</text>", "<text>2</text>"],
gap: 60,
direction: "column",
});
expect(columns).toStrictEqual([
`<g transform="translate(0, 0)"><text>1</text></g>`,
`<g transform="translate(0, 60)"><text>2</text></g>`,
]);
});
it("should work with sizes", () => {
const layout = flexLayout({
items: [
"<text>1</text>",
"<text>2</text>",
"<text>3</text>",
"<text>4</text>",
],
gap: 20,
sizes: [200, 100, 55, 25],
});
expect(layout).toStrictEqual([
`<g transform="translate(0, 0)"><text>1</text></g>`,
`<g transform="translate(220, 0)"><text>2</text></g>`,
`<g transform="translate(340, 0)"><text>3</text></g>`,
`<g transform="translate(415, 0)"><text>4</text></g>`,
]);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/status.up.test.js | tests/status.up.test.js | /**
* @file Tests for the status/up cloud function.
*/
import { afterEach, describe, expect, it, jest } from "@jest/globals";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import up, { RATE_LIMIT_SECONDS } from "../api/status/up.js";
const mock = new MockAdapter(axios);
const successData = {
rateLimit: {
remaining: 4986,
},
};
const faker = (query) => {
const req = {
query: { ...query },
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
return { req, res };
};
const rate_limit_error = {
errors: [
{
type: "RATE_LIMITED",
},
],
};
const bad_credentials_error = {
message: "Bad credentials",
};
const shields_up = {
schemaVersion: 1,
label: "Public Instance",
isError: true,
message: "up",
color: "brightgreen",
};
const shields_down = {
schemaVersion: 1,
label: "Public Instance",
isError: true,
message: "down",
color: "red",
};
afterEach(() => {
mock.reset();
});
describe("Test /api/status/up", () => {
it("should return `true` if request was successful", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(true);
});
it("should return `false` if all PATs are rate limited", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(false);
});
it("should return JSON `true` if request was successful and type='json'", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({ type: "json" }, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith({ up: true });
});
it("should return JSON `false` if all PATs are rate limited and type='json'", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({ type: "json" }, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith({ up: false });
});
it("should return UP shields.io config if request was successful and type='shields'", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({ type: "shields" }, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(shields_up);
});
it("should return DOWN shields.io config if all PATs are rate limited and type='shields'", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({ type: "shields" }, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(shields_down);
});
it("should return `true` if the first PAT is rate limited but the second PATs works", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, rate_limit_error)
.onPost("https://api.github.com/graphql")
.replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(true);
});
it("should return `true` if the first PAT has 'Bad credentials' but the second PAT works", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(404, bad_credentials_error)
.onPost("https://api.github.com/graphql")
.replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(true);
});
it("should return `false` if all pats have 'Bad credentials'", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(404, bad_credentials_error);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(false);
});
it("should throw an error if the request fails", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toHaveBeenCalledWith(
"Content-Type",
"application/json",
);
expect(res.send).toHaveBeenCalledWith(false);
});
it("should have proper cache when no error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`],
]);
});
it("should have proper cache when error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", "no-store"],
]);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/wakatime.test.js | tests/wakatime.test.js | import { afterEach, describe, expect, it, jest } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import wakatime from "../api/wakatime.js";
import { renderWakatimeCard } from "../src/cards/wakatime.js";
import { CACHE_TTL, DURATIONS } from "../src/common/cache.js";
const wakaTimeData = {
data: {
categories: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "Coding",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
daily_average: 16095,
daily_average_including_other_language: 16329,
days_including_holidays: 7,
days_minus_holidays: 5,
editors: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "VS Code",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
holidays: 2,
human_readable_daily_average: "4 hrs 28 mins",
human_readable_daily_average_including_other_language: "4 hrs 32 mins",
human_readable_total: "22 hrs 21 mins",
human_readable_total_including_other_language: "22 hrs 40 mins",
id: "random hash",
is_already_updating: false,
is_coding_activity_visible: true,
is_including_today: false,
is_other_usage_visible: true,
is_stuck: false,
is_up_to_date: true,
languages: [
{
digital: "0:19",
hours: 0,
minutes: 19,
name: "Other",
percent: 1.43,
text: "19 mins",
total_seconds: 1170.434361,
},
{
digital: "0:01",
hours: 0,
minutes: 1,
name: "TypeScript",
percent: 0.1,
text: "1 min",
total_seconds: 83.293809,
},
{
digital: "0:00",
hours: 0,
minutes: 0,
name: "YAML",
percent: 0.07,
text: "0 secs",
total_seconds: 54.975151,
},
],
operating_systems: [
{
digital: "22:40",
hours: 22,
minutes: 40,
name: "Mac",
percent: 100,
text: "22 hrs 40 mins",
total_seconds: 81643.570077,
},
],
percent_calculated: 100,
range: "last_7_days",
status: "ok",
timeout: 15,
total_seconds: 80473.135716,
total_seconds_including_other_language: 81643.570077,
user_id: "random hash",
username: "anuraghazra",
writes_only: false,
},
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test /api/wakatime", () => {
it("should test the request", async () => {
const username = "anuraghazra";
const req = { query: { username } };
const res = { setHeader: jest.fn(), send: jest.fn() };
mock
.onGet(
`https://wakatime.com/api/v1/users/${username}/stats?is_including_today=true`,
)
.reply(200, wakaTimeData);
await wakatime(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toHaveBeenCalledWith(
renderWakatimeCard(wakaTimeData.data, {}),
);
});
it("should have proper cache", async () => {
const username = "anuraghazra";
const req = { query: { username } };
const res = { setHeader: jest.fn(), send: jest.fn() };
mock
.onGet(
`https://wakatime.com/api/v1/users/${username}/stats?is_including_today=true`,
)
.reply(200, wakaTimeData);
await wakatime(req, res);
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/svg+xml");
expect(res.setHeader).toHaveBeenCalledWith(
"Cache-Control",
`max-age=${CACHE_TTL.WAKATIME_CARD.DEFAULT}, ` +
`s-maxage=${CACHE_TTL.WAKATIME_CARD.DEFAULT}, ` +
`stale-while-revalidate=${DURATIONS.ONE_DAY}`,
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/calculateRank.test.js | tests/calculateRank.test.js | import { describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import { calculateRank } from "../src/calculateRank.js";
describe("Test calculateRank", () => {
it("new user gets C rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 0,
prs: 0,
issues: 0,
reviews: 0,
repos: 0,
stars: 0,
followers: 0,
}),
).toStrictEqual({ level: "C", percentile: 100 });
});
it("beginner user gets B- rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 125,
prs: 25,
issues: 10,
reviews: 5,
repos: 0,
stars: 25,
followers: 5,
}),
).toStrictEqual({ level: "B-", percentile: 65.02918514848255 });
});
it("median user gets B+ rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 250,
prs: 50,
issues: 25,
reviews: 10,
repos: 0,
stars: 50,
followers: 10,
}),
).toStrictEqual({ level: "B+", percentile: 46.09375 });
});
it("average user gets B+ rank (include_all_commits)", () => {
expect(
calculateRank({
all_commits: true,
commits: 1000,
prs: 50,
issues: 25,
reviews: 10,
repos: 0,
stars: 50,
followers: 10,
}),
).toStrictEqual({ level: "B+", percentile: 46.09375 });
});
it("advanced user gets A rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 500,
prs: 100,
issues: 50,
reviews: 20,
repos: 0,
stars: 200,
followers: 40,
}),
).toStrictEqual({ level: "A", percentile: 20.841471354166664 });
});
it("expert user gets A+ rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 1000,
prs: 200,
issues: 100,
reviews: 40,
repos: 0,
stars: 800,
followers: 160,
}),
).toStrictEqual({ level: "A+", percentile: 5.575988339442828 });
});
it("sindresorhus gets S rank", () => {
expect(
calculateRank({
all_commits: false,
commits: 1300,
prs: 1500,
issues: 4500,
reviews: 1000,
repos: 0,
stars: 600000,
followers: 50000,
}),
).toStrictEqual({ level: "S", percentile: 0.4578556547153667 });
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/fetchGist.test.js | tests/fetchGist.test.js | import { afterEach, describe, expect, it } from "@jest/globals";
import "@testing-library/jest-dom";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { fetchGist } from "../src/fetchers/gist.js";
const gist_data = {
data: {
viewer: {
gist: {
description:
"List of countries and territories in English and Spanish: name, continent, capital, dial code, country codes, TLD, and area in sq km. Lista de países y territorios en Inglés y Español: nombre, continente, capital, código de teléfono, códigos de país, dominio y área en km cuadrados. Updated 2023",
owner: {
login: "Yizack",
},
stargazerCount: 33,
forks: {
totalCount: 11,
},
files: [
{
name: "countries.json",
language: {
name: "JSON",
},
size: 85858,
},
{
name: "territories.txt",
language: {
name: "Text",
},
size: 87858,
},
{
name: "countries_spanish.json",
language: {
name: "JSON",
},
size: 85858,
},
{
name: "territories_spanish.txt",
language: {
name: "Text",
},
size: 87858,
},
],
},
},
},
};
const gist_not_found_data = {
data: {
viewer: {
gist: null,
},
},
};
const gist_errors_data = {
errors: [
{
message: "Some test GraphQL error",
},
],
};
const mock = new MockAdapter(axios);
afterEach(() => {
mock.reset();
});
describe("Test fetchGist", () => {
it("should fetch gist correctly", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, gist_data);
let gist = await fetchGist("bbfce31e0217a3689c8d961a356cb10d");
expect(gist).toStrictEqual({
name: "countries.json",
nameWithOwner: "Yizack/countries.json",
description:
"List of countries and territories in English and Spanish: name, continent, capital, dial code, country codes, TLD, and area in sq km. Lista de países y territorios en Inglés y Español: nombre, continente, capital, código de teléfono, códigos de país, dominio y área en km cuadrados. Updated 2023",
language: "Text",
starsCount: 33,
forksCount: 11,
});
});
it("should throw correct error if gist not found", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(200, gist_not_found_data);
await expect(fetchGist("bbfce31e0217a3689c8d961a356cb10d")).rejects.toThrow(
"Gist not found",
);
});
it("should throw error if reaponse contains them", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, gist_errors_data);
await expect(fetchGist("bbfce31e0217a3689c8d961a356cb10d")).rejects.toThrow(
"Some test GraphQL error",
);
});
it("should throw error if id is not provided", async () => {
await expect(fetchGist()).rejects.toThrow(
'Missing params "id" make sure you pass the parameters in URL',
);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/bench/gist.bench.js | tests/bench/gist.bench.js | import gist from "../../api/gist.js";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { it, jest } from "@jest/globals";
import { runAndLogStats } from "./utils.js";
const gist_data = {
data: {
viewer: {
gist: {
description:
"List of countries and territories in English and Spanish: name, continent, capital, dial code, country codes, TLD, and area in sq km. Lista de países y territorios en Inglés y Español: nombre, continente, capital, código de teléfono, códigos de país, dominio y área en km cuadrados. Updated 2023",
owner: {
login: "Yizack",
},
stargazerCount: 33,
forks: {
totalCount: 11,
},
files: [
{
name: "countries.json",
language: {
name: "JSON",
},
size: 85858,
},
],
},
},
},
};
const mock = new MockAdapter(axios);
mock.onPost("https://api.github.com/graphql").reply(200, gist_data);
it("test /api/gist", async () => {
await runAndLogStats("test /api/gist", async () => {
const req = {
query: {
id: "bbfce31e0217a3689c8d961a356cb10d",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
await gist(req, res);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/bench/pin.bench.js | tests/bench/pin.bench.js | import pin from "../../api/pin.js";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { it, jest } from "@jest/globals";
import { runAndLogStats } from "./utils.js";
const data_repo = {
repository: {
username: "anuraghazra",
name: "convoychat",
stargazers: {
totalCount: 38000,
},
description: "Help us take over the world! React + TS + GraphQL Chat App",
primaryLanguage: {
color: "#2b7489",
id: "MDg6TGFuZ3VhZ2UyODc=",
name: "TypeScript",
},
forkCount: 100,
isTemplate: false,
},
};
const data_user = {
data: {
user: { repository: data_repo.repository },
organization: null,
},
};
const mock = new MockAdapter(axios);
mock.onPost("https://api.github.com/graphql").reply(200, data_user);
it("test /api/pin", async () => {
await runAndLogStats("test /api/pin", async () => {
const req = {
query: {
username: "anuraghazra",
repo: "convoychat",
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
await pin(req, res);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/bench/calculateRank.bench.js | tests/bench/calculateRank.bench.js | import { calculateRank } from "../../src/calculateRank.js";
import { it } from "@jest/globals";
import { runAndLogStats } from "./utils.js";
it("calculateRank", async () => {
await runAndLogStats("calculateRank", () => {
calculateRank({
all_commits: false,
commits: 1300,
prs: 1500,
issues: 4500,
reviews: 1000,
repos: 0,
stars: 600000,
followers: 50000,
});
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/bench/api.bench.js | tests/bench/api.bench.js | import api from "../../api/index.js";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { it, jest } from "@jest/globals";
import { runAndLogStats } from "./utils.js";
const stats = {
name: "Anurag Hazra",
totalStars: 100,
totalCommits: 200,
totalIssues: 300,
totalPRs: 400,
totalPRsMerged: 320,
mergedPRsPercentage: 80,
totalReviews: 50,
totalDiscussionsStarted: 10,
totalDiscussionsAnswered: 40,
contributedTo: 50,
rank: null,
};
const data_stats = {
data: {
user: {
name: stats.name,
repositoriesContributedTo: { totalCount: stats.contributedTo },
commits: {
totalCommitContributions: stats.totalCommits,
},
reviews: {
totalPullRequestReviewContributions: stats.totalReviews,
},
pullRequests: { totalCount: stats.totalPRs },
mergedPullRequests: { totalCount: stats.totalPRsMerged },
openIssues: { totalCount: stats.totalIssues },
closedIssues: { totalCount: 0 },
followers: { totalCount: 0 },
repositoryDiscussions: { totalCount: stats.totalDiscussionsStarted },
repositoryDiscussionComments: {
totalCount: stats.totalDiscussionsAnswered,
},
repositories: {
totalCount: 1,
nodes: [{ stargazers: { totalCount: 100 } }],
pageInfo: {
hasNextPage: false,
endCursor: "cursor",
},
},
},
},
};
const mock = new MockAdapter(axios);
const faker = (query, data) => {
const req = {
query: {
username: "anuraghazra",
...query,
},
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
mock.onPost("https://api.github.com/graphql").replyOnce(200, data);
return { req, res };
};
it("test /api", async () => {
await runAndLogStats("test /api", async () => {
const { req, res } = faker({}, data_stats);
await api(req, res);
});
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/bench/utils.js | tests/bench/utils.js | // @ts-check
const DEFAULT_RUNS = 1000;
const DEFAULT_WARMUPS = 50;
/**
* Formats a duration in nanoseconds to a compact human-readable string.
*
* @param {bigint} ns Duration in nanoseconds.
* @returns {string} Formatted time string.
*/
const formatTime = (ns) => {
if (ns < 1_000n) {
return `${ns}ns`;
}
if (ns < 1_000_000n) {
return `${Number(ns) / 1_000}µs`;
}
if (ns < 1_000_000_000n) {
return `${(Number(ns) / 1_000_000).toFixed(3)}ms`;
}
return `${(Number(ns) / 1_000_000_000).toFixed(3)}s`;
};
/**
* Measures synchronous or async function execution time.
*
* @param {Function} fn Function to measure.
* @returns {Promise<bigint>} elapsed nanoseconds
*/
const measurePerformance = async (fn) => {
const start = process.hrtime.bigint();
const ret = fn();
if (ret instanceof Promise) {
await ret;
}
const end = process.hrtime.bigint();
return end - start;
};
/**
* Computes basic & extended statistics.
*
* @param {bigint[]} samples Array of samples in nanoseconds.
* @returns {object} Stats
*/
const computeStats = (samples) => {
const sorted = [...samples].sort((a, b) => (a < b ? -1 : 1));
const toNumber = (b) => Number(b); // safe for typical short benches
const n = sorted.length;
const sum = sorted.reduce((a, b) => a + b, 0n);
const avg = Number(sum) / n;
const median =
n % 2
? toNumber(sorted[(n - 1) / 2])
: (toNumber(sorted[n / 2 - 1]) + toNumber(sorted[n / 2])) / 2;
const p = (q) => {
const idx = Math.min(n - 1, Math.floor((q / 100) * n));
return toNumber(sorted[idx]);
};
const min = toNumber(sorted[0]);
const max = toNumber(sorted[n - 1]);
const variance =
sorted.reduce((acc, v) => acc + (toNumber(v) - avg) ** 2, 0) / n;
const stdev = Math.sqrt(variance);
return {
runs: n,
min,
max,
average: avg,
median,
p75: p(75),
p95: p(95),
p99: p(99),
stdev,
totalTime: toNumber(sum),
};
};
/**
* Benchmark a function.
*
* @param {string} fnName Name of the function (for logging).
* @param {Function} fn Function to benchmark.
* @param {object} [opts] Options.
* @param {number} [opts.runs] Number of measured runs.
* @param {number} [opts.warmup] Warm-up iterations (not measured).
* @param {boolean} [opts.trimOutliers] Drop top & bottom 1% before stats.
* @returns {Promise<object>} Stats (nanoseconds for core metrics).
*/
export const runAndLogStats = async (
fnName,
fn,
{ runs = DEFAULT_RUNS, warmup = DEFAULT_WARMUPS, trimOutliers = false } = {},
) => {
if (runs <= 0) {
throw new Error("Number of runs must be positive.");
}
// Warm-up
for (let i = 0; i < warmup; i++) {
const ret = fn();
if (ret instanceof Promise) {
await ret;
}
}
const samples = [];
for (let i = 0; i < runs; i++) {
samples.push(await measurePerformance(fn));
}
let processed = samples;
if (trimOutliers && samples.length > 10) {
const sorted = [...samples].sort((a, b) => (a < b ? -1 : 1));
const cut = Math.max(1, Math.floor(sorted.length * 0.01));
processed = sorted.slice(cut, sorted.length - cut);
}
const stats = computeStats(processed);
const fmt = (ns) => formatTime(BigInt(Math.round(ns)));
console.log(
`${fnName} | runs=${stats.runs} avg=${fmt(stats.average)} median=${fmt(
stats.median,
)} p95=${fmt(stats.p95)} min=${fmt(stats.min)} max=${fmt(
stats.max,
)} stdev=${fmt(stats.stdev)}`,
);
return stats;
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/tests/e2e/e2e.test.js | tests/e2e/e2e.test.js | /**
* @file Contains end-to-end tests for the Vercel preview instance.
*/
import dotenv from "dotenv";
dotenv.config();
import { beforeAll, describe, expect, test } from "@jest/globals";
import axios from "axios";
import { renderGistCard } from "../../src/cards/gist.js";
import { renderRepoCard } from "../../src/cards/repo.js";
import { renderStatsCard } from "../../src/cards/stats.js";
import { renderTopLanguages } from "../../src/cards/top-languages.js";
import { renderWakatimeCard } from "../../src/cards/wakatime.js";
const REPO = "curly-fiesta";
const USER = "catelinemnemosyne";
const STATS_CARD_USER = "e2eninja";
const GIST_ID = "372cef55fd897b31909fdeb3a7262758";
const STATS_DATA = {
name: "CodeNinja",
totalPRs: 1,
totalReviews: 0,
totalCommits: 3,
totalIssues: 1,
totalStars: 1,
contributedTo: 0,
rank: {
level: "C",
percentile: 98.73972605284538,
},
};
const LANGS_DATA = {
HTML: {
color: "#e34c26",
name: "HTML",
size: 1721,
},
CSS: {
color: "#663399",
name: "CSS",
size: 930,
},
JavaScript: {
color: "#f1e05a",
name: "JavaScript",
size: 1912,
},
};
const WAKATIME_DATA = {
human_readable_range: "last week",
is_already_updating: false,
is_coding_activity_visible: true,
is_including_today: false,
is_other_usage_visible: false,
is_stuck: false,
is_up_to_date: false,
is_up_to_date_pending_future: false,
percent_calculated: 0,
range: "all_time",
status: "pending_update",
timeout: 15,
username: USER,
writes_only: false,
};
const REPOSITORY_DATA = {
name: REPO,
nameWithOwner: `${USER}/cra-test`,
isPrivate: false,
isArchived: false,
isTemplate: false,
stargazers: {
totalCount: 1,
},
description: "Simple cra test repo.",
primaryLanguage: {
color: "#f1e05a",
id: "MDg6TGFuZ3VhZ2UxNDA=",
name: "JavaScript",
},
forkCount: 0,
starCount: 1,
};
/**
* @typedef {import("../../src/fetchers/types").GistData} GistData Gist data type.
*/
/**
* @type {GistData}
*/
const GIST_DATA = {
name: "link.txt",
nameWithOwner: "qwerty541/link.txt",
description:
"Trying to access this path on Windows 10 ver. 1803+ will breaks NTFS",
language: "Text",
starsCount: 1,
forksCount: 0,
};
const CACHE_BURST_STRING = `v=${new Date().getTime()}`;
describe("Fetch Cards", () => {
let VERCEL_PREVIEW_URL;
beforeAll(() => {
process.env.NODE_ENV = "development";
VERCEL_PREVIEW_URL = process.env.VERCEL_PREVIEW_URL;
});
test("retrieve stats card", async () => {
expect(VERCEL_PREVIEW_URL).toBeDefined();
// Check if the Vercel preview instance stats card function is up and running.
await expect(
axios.get(`${VERCEL_PREVIEW_URL}/api?username=${STATS_CARD_USER}`),
).resolves.not.toThrow();
// Get local stats card.
const localStatsCardSVG = renderStatsCard(STATS_DATA, {
include_all_commits: true,
});
// Get the Vercel preview stats card response.
const serverStatsSvg = await axios.get(
`${VERCEL_PREVIEW_URL}/api?username=${STATS_CARD_USER}&include_all_commits=true&${CACHE_BURST_STRING}`,
);
// Check if stats card from deployment matches the stats card from local.
expect(serverStatsSvg.data).toEqual(localStatsCardSVG);
}, 15000);
test("retrieve language card", async () => {
expect(VERCEL_PREVIEW_URL).toBeDefined();
// Check if the Vercel preview instance language card function is up and running.
console.log(
`${VERCEL_PREVIEW_URL}/api/top-langs/?username=${USER}&${CACHE_BURST_STRING}`,
);
await expect(
axios.get(
`${VERCEL_PREVIEW_URL}/api/top-langs/?username=${USER}&${CACHE_BURST_STRING}`,
),
).resolves.not.toThrow();
// Get local language card.
const localLanguageCardSVG = renderTopLanguages(LANGS_DATA);
// Get the Vercel preview language card response.
const severLanguageSVG = await axios.get(
`${VERCEL_PREVIEW_URL}/api/top-langs/?username=${USER}&${CACHE_BURST_STRING}`,
);
// Check if language card from deployment matches the local language card.
expect(severLanguageSVG.data).toEqual(localLanguageCardSVG);
}, 15000);
test("retrieve WakaTime card", async () => {
expect(VERCEL_PREVIEW_URL).toBeDefined();
// Check if the Vercel preview instance WakaTime function is up and running.
await expect(
axios.get(`${VERCEL_PREVIEW_URL}/api/wakatime?username=${USER}`),
).resolves.not.toThrow();
// Get local WakaTime card.
const localWakaCardSVG = renderWakatimeCard(WAKATIME_DATA);
// Get the Vercel preview WakaTime card response.
const serverWakaTimeSvg = await axios.get(
`${VERCEL_PREVIEW_URL}/api/wakatime?username=${USER}&${CACHE_BURST_STRING}`,
);
// Check if WakaTime card from deployment matches the local WakaTime card.
expect(serverWakaTimeSvg.data).toEqual(localWakaCardSVG);
}, 15000);
test("retrieve repo card", async () => {
expect(VERCEL_PREVIEW_URL).toBeDefined();
// Check if the Vercel preview instance Repo function is up and running.
await expect(
axios.get(
`${VERCEL_PREVIEW_URL}/api/pin/?username=${USER}&repo=${REPO}&${CACHE_BURST_STRING}`,
),
).resolves.not.toThrow();
// Get local repo card.
const localRepoCardSVG = renderRepoCard(REPOSITORY_DATA);
// Get the Vercel preview repo card response.
const serverRepoSvg = await axios.get(
`${VERCEL_PREVIEW_URL}/api/pin/?username=${USER}&repo=${REPO}&${CACHE_BURST_STRING}`,
);
// Check if Repo card from deployment matches the local Repo card.
expect(serverRepoSvg.data).toEqual(localRepoCardSVG);
}, 15000);
test("retrieve gist card", async () => {
expect(VERCEL_PREVIEW_URL).toBeDefined();
// Check if the Vercel preview instance Gist function is up and running.
await expect(
axios.get(
`${VERCEL_PREVIEW_URL}/api/gist?id=${GIST_ID}&${CACHE_BURST_STRING}`,
),
).resolves.not.toThrow();
// Get local gist card.
const localGistCardSVG = renderGistCard(GIST_DATA);
// Get the Vercel preview gist card response.
const serverGistSvg = await axios.get(
`${VERCEL_PREVIEW_URL}/api/gist?id=${GIST_ID}&${CACHE_BURST_STRING}`,
);
// Check if Gist card from deployment matches the local Gist card.
expect(serverGistSvg.data).toEqual(localGistCardSVG);
}, 15000);
});
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/gist.js | api/gist.js | // @ts-check
import { renderError } from "../src/common/render.js";
import { isLocaleAvailable } from "../src/translations.js";
import { renderGistCard } from "../src/cards/gist.js";
import { fetchGist } from "../src/fetchers/gist.js";
import {
CACHE_TTL,
resolveCacheSeconds,
setCacheHeaders,
setErrorCacheHeaders,
} from "../src/common/cache.js";
import { guardAccess } from "../src/common/access.js";
import {
MissingParamError,
retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseBoolean } from "../src/common/ops.js";
// @ts-ignore
export default async (req, res) => {
const {
id,
title_color,
icon_color,
text_color,
bg_color,
theme,
cache_seconds,
locale,
border_radius,
border_color,
show_owner,
hide_border,
} = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const access = guardAccess({
res,
id,
type: "gist",
colors: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
});
if (!access.isPassed) {
return access.result;
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
try {
const gistData = await fetchGist(id);
const cacheSeconds = resolveCacheSeconds({
requested: parseInt(cache_seconds, 10),
def: CACHE_TTL.GIST_CARD.DEFAULT,
min: CACHE_TTL.GIST_CARD.MIN,
max: CACHE_TTL.GIST_CARD.MAX,
});
setCacheHeaders(res, cacheSeconds);
return res.send(
renderGistCard(gistData, {
title_color,
icon_color,
text_color,
bg_color,
theme,
border_radius,
border_color,
locale: locale ? locale.toLowerCase() : null,
show_owner: parseBoolean(show_owner),
hide_border: parseBoolean(hide_border),
}),
);
} catch (err) {
setErrorCacheHeaders(res);
if (err instanceof Error) {
return res.send(
renderError({
message: err.message,
secondaryMessage: retrieveSecondaryMessage(err),
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
show_repo_link: !(err instanceof MissingParamError),
},
}),
);
}
return res.send(
renderError({
message: "An unknown error occurred",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/index.js | api/index.js | // @ts-check
import { renderStatsCard } from "../src/cards/stats.js";
import { guardAccess } from "../src/common/access.js";
import {
CACHE_TTL,
resolveCacheSeconds,
setCacheHeaders,
setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
MissingParamError,
retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchStats } from "../src/fetchers/stats.js";
import { isLocaleAvailable } from "../src/translations.js";
// @ts-ignore
export default async (req, res) => {
const {
username,
hide,
hide_title,
hide_border,
card_width,
hide_rank,
show_icons,
include_all_commits,
commits_year,
line_height,
title_color,
ring_color,
icon_color,
text_color,
text_bold,
bg_color,
theme,
cache_seconds,
exclude_repo,
custom_title,
locale,
disable_animations,
border_radius,
number_format,
number_precision,
border_color,
rank_icon,
show,
} = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const access = guardAccess({
res,
id: username,
type: "username",
colors: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
});
if (!access.isPassed) {
return access.result;
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
try {
const showStats = parseArray(show);
const stats = await fetchStats(
username,
parseBoolean(include_all_commits),
parseArray(exclude_repo),
showStats.includes("prs_merged") ||
showStats.includes("prs_merged_percentage"),
showStats.includes("discussions_started"),
showStats.includes("discussions_answered"),
parseInt(commits_year, 10),
);
const cacheSeconds = resolveCacheSeconds({
requested: parseInt(cache_seconds, 10),
def: CACHE_TTL.STATS_CARD.DEFAULT,
min: CACHE_TTL.STATS_CARD.MIN,
max: CACHE_TTL.STATS_CARD.MAX,
});
setCacheHeaders(res, cacheSeconds);
return res.send(
renderStatsCard(stats, {
hide: parseArray(hide),
show_icons: parseBoolean(show_icons),
hide_title: parseBoolean(hide_title),
hide_border: parseBoolean(hide_border),
card_width: parseInt(card_width, 10),
hide_rank: parseBoolean(hide_rank),
include_all_commits: parseBoolean(include_all_commits),
commits_year: parseInt(commits_year, 10),
line_height,
title_color,
ring_color,
icon_color,
text_color,
text_bold: parseBoolean(text_bold),
bg_color,
theme,
custom_title,
border_radius,
border_color,
number_format,
number_precision: parseInt(number_precision, 10),
locale: locale ? locale.toLowerCase() : null,
disable_animations: parseBoolean(disable_animations),
rank_icon,
show: showStats,
}),
);
} catch (err) {
setErrorCacheHeaders(res);
if (err instanceof Error) {
return res.send(
renderError({
message: err.message,
secondaryMessage: retrieveSecondaryMessage(err),
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
show_repo_link: !(err instanceof MissingParamError),
},
}),
);
}
return res.send(
renderError({
message: "An unknown error occurred",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/top-langs.js | api/top-langs.js | // @ts-check
import { renderTopLanguages } from "../src/cards/top-languages.js";
import { guardAccess } from "../src/common/access.js";
import {
CACHE_TTL,
resolveCacheSeconds,
setCacheHeaders,
setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
MissingParamError,
retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchTopLanguages } from "../src/fetchers/top-languages.js";
import { isLocaleAvailable } from "../src/translations.js";
// @ts-ignore
export default async (req, res) => {
const {
username,
hide,
hide_title,
hide_border,
card_width,
title_color,
text_color,
bg_color,
theme,
cache_seconds,
layout,
langs_count,
exclude_repo,
size_weight,
count_weight,
custom_title,
locale,
border_radius,
border_color,
disable_animations,
hide_progress,
stats_format,
} = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const access = guardAccess({
res,
id: username,
type: "username",
colors: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
});
if (!access.isPassed) {
return access.result;
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Locale not found",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
if (
layout !== undefined &&
(typeof layout !== "string" ||
!["compact", "normal", "donut", "donut-vertical", "pie"].includes(layout))
) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Incorrect layout input",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
if (
stats_format !== undefined &&
(typeof stats_format !== "string" ||
!["bytes", "percentages"].includes(stats_format))
) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Incorrect stats_format input",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
try {
const topLangs = await fetchTopLanguages(
username,
parseArray(exclude_repo),
size_weight,
count_weight,
);
const cacheSeconds = resolveCacheSeconds({
requested: parseInt(cache_seconds, 10),
def: CACHE_TTL.TOP_LANGS_CARD.DEFAULT,
min: CACHE_TTL.TOP_LANGS_CARD.MIN,
max: CACHE_TTL.TOP_LANGS_CARD.MAX,
});
setCacheHeaders(res, cacheSeconds);
return res.send(
renderTopLanguages(topLangs, {
custom_title,
hide_title: parseBoolean(hide_title),
hide_border: parseBoolean(hide_border),
card_width: parseInt(card_width, 10),
hide: parseArray(hide),
title_color,
text_color,
bg_color,
theme,
layout,
langs_count,
border_radius,
border_color,
locale: locale ? locale.toLowerCase() : null,
disable_animations: parseBoolean(disable_animations),
hide_progress: parseBoolean(hide_progress),
stats_format,
}),
);
} catch (err) {
setErrorCacheHeaders(res);
if (err instanceof Error) {
return res.send(
renderError({
message: err.message,
secondaryMessage: retrieveSecondaryMessage(err),
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
show_repo_link: !(err instanceof MissingParamError),
},
}),
);
}
return res.send(
renderError({
message: "An unknown error occurred",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/wakatime.js | api/wakatime.js | // @ts-check
import { renderWakatimeCard } from "../src/cards/wakatime.js";
import { renderError } from "../src/common/render.js";
import { fetchWakatimeStats } from "../src/fetchers/wakatime.js";
import { isLocaleAvailable } from "../src/translations.js";
import {
CACHE_TTL,
resolveCacheSeconds,
setCacheHeaders,
setErrorCacheHeaders,
} from "../src/common/cache.js";
import { guardAccess } from "../src/common/access.js";
import {
MissingParamError,
retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseArray, parseBoolean } from "../src/common/ops.js";
// @ts-ignore
export default async (req, res) => {
const {
username,
title_color,
icon_color,
hide_border,
card_width,
line_height,
text_color,
bg_color,
theme,
cache_seconds,
hide_title,
hide_progress,
custom_title,
locale,
layout,
langs_count,
hide,
api_domain,
border_radius,
border_color,
display_format,
disable_animations,
} = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const access = guardAccess({
res,
id: username,
type: "wakatime",
colors: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
});
if (!access.isPassed) {
return access.result;
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
try {
const stats = await fetchWakatimeStats({ username, api_domain });
const cacheSeconds = resolveCacheSeconds({
requested: parseInt(cache_seconds, 10),
def: CACHE_TTL.WAKATIME_CARD.DEFAULT,
min: CACHE_TTL.WAKATIME_CARD.MIN,
max: CACHE_TTL.WAKATIME_CARD.MAX,
});
setCacheHeaders(res, cacheSeconds);
return res.send(
renderWakatimeCard(stats, {
custom_title,
hide_title: parseBoolean(hide_title),
hide_border: parseBoolean(hide_border),
card_width: parseInt(card_width, 10),
hide: parseArray(hide),
line_height,
title_color,
icon_color,
text_color,
bg_color,
theme,
hide_progress,
border_radius,
border_color,
locale: locale ? locale.toLowerCase() : null,
layout,
langs_count,
display_format,
disable_animations: parseBoolean(disable_animations),
}),
);
} catch (err) {
setErrorCacheHeaders(res);
if (err instanceof Error) {
return res.send(
renderError({
message: err.message,
secondaryMessage: retrieveSecondaryMessage(err),
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
show_repo_link: !(err instanceof MissingParamError),
},
}),
);
}
return res.send(
renderError({
message: "An unknown error occurred",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/pin.js | api/pin.js | // @ts-check
import { renderRepoCard } from "../src/cards/repo.js";
import { guardAccess } from "../src/common/access.js";
import {
CACHE_TTL,
resolveCacheSeconds,
setCacheHeaders,
setErrorCacheHeaders,
} from "../src/common/cache.js";
import {
MissingParamError,
retrieveSecondaryMessage,
} from "../src/common/error.js";
import { parseBoolean } from "../src/common/ops.js";
import { renderError } from "../src/common/render.js";
import { fetchRepo } from "../src/fetchers/repo.js";
import { isLocaleAvailable } from "../src/translations.js";
// @ts-ignore
export default async (req, res) => {
const {
username,
repo,
hide_border,
title_color,
icon_color,
text_color,
bg_color,
theme,
show_owner,
cache_seconds,
locale,
border_radius,
border_color,
description_lines_count,
} = req.query;
res.setHeader("Content-Type", "image/svg+xml");
const access = guardAccess({
res,
id: username,
type: "username",
colors: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
});
if (!access.isPassed) {
return access.result;
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError({
message: "Something went wrong",
secondaryMessage: "Language not found",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
try {
const repoData = await fetchRepo(username, repo);
const cacheSeconds = resolveCacheSeconds({
requested: parseInt(cache_seconds, 10),
def: CACHE_TTL.PIN_CARD.DEFAULT,
min: CACHE_TTL.PIN_CARD.MIN,
max: CACHE_TTL.PIN_CARD.MAX,
});
setCacheHeaders(res, cacheSeconds);
return res.send(
renderRepoCard(repoData, {
hide_border: parseBoolean(hide_border),
title_color,
icon_color,
text_color,
bg_color,
theme,
border_radius,
border_color,
show_owner: parseBoolean(show_owner),
locale: locale ? locale.toLowerCase() : null,
description_lines_count,
}),
);
} catch (err) {
setErrorCacheHeaders(res);
if (err instanceof Error) {
return res.send(
renderError({
message: err.message,
secondaryMessage: retrieveSecondaryMessage(err),
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
show_repo_link: !(err instanceof MissingParamError),
},
}),
);
}
return res.send(
renderError({
message: "An unknown error occurred",
renderOptions: {
title_color,
text_color,
bg_color,
border_color,
theme,
},
}),
);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/status/pat-info.js | api/status/pat-info.js | // @ts-check
/**
* @file Contains a simple cloud function that can be used to check which PATs are no
* longer working. It returns a list of valid PATs, expired PATs and PATs with errors.
*
* @description This function is currently rate limited to 1 request per 5 minutes.
*/
import { request } from "../../src/common/http.js";
import { logger } from "../../src/common/log.js";
import { dateDiff } from "../../src/common/ops.js";
export const RATE_LIMIT_SECONDS = 60 * 5; // 1 request per 5 minutes
/**
* Simple uptime check fetcher for the PATs.
*
* @param {any} variables Fetcher variables.
* @param {string} token GitHub token.
* @returns {Promise<import('axios').AxiosResponse>} The response.
*/
const uptimeFetcher = (variables, token) => {
return request(
{
query: `
query {
rateLimit {
remaining
resetAt
},
}`,
variables,
},
{
Authorization: `bearer ${token}`,
},
);
};
const getAllPATs = () => {
return Object.keys(process.env).filter((key) => /PAT_\d*$/.exec(key));
};
/**
* @typedef {(variables: any, token: string) => Promise<import('axios').AxiosResponse>} Fetcher The fetcher function.
* @typedef {{validPATs: string[], expiredPATs: string[], exhaustedPATs: string[], suspendedPATs: string[], errorPATs: string[], details: any}} PATInfo The PAT info.
*/
/**
* Check whether any of the PATs is expired.
*
* @param {Fetcher} fetcher The fetcher function.
* @param {any} variables Fetcher variables.
* @returns {Promise<PATInfo>} The response.
*/
const getPATInfo = async (fetcher, variables) => {
/** @type {Record<string, any>} */
const details = {};
const PATs = getAllPATs();
for (const pat of PATs) {
try {
const response = await fetcher(variables, process.env[pat]);
const errors = response.data.errors;
const hasErrors = Boolean(errors);
const errorType = errors?.[0]?.type;
const isRateLimited =
(hasErrors && errorType === "RATE_LIMITED") ||
response.data.data?.rateLimit?.remaining === 0;
// Store PATs with errors.
if (hasErrors && errorType !== "RATE_LIMITED") {
details[pat] = {
status: "error",
error: {
type: errors[0].type,
message: errors[0].message,
},
};
continue;
} else if (isRateLimited) {
const date1 = new Date();
const date2 = new Date(response.data?.data?.rateLimit?.resetAt);
details[pat] = {
status: "exhausted",
remaining: 0,
resetIn: dateDiff(date2, date1) + " minutes",
};
} else {
details[pat] = {
status: "valid",
remaining: response.data.data.rateLimit.remaining,
};
}
} catch (err) {
// Store the PAT if it is expired.
const errorMessage = err.response?.data?.message?.toLowerCase();
if (errorMessage === "bad credentials") {
details[pat] = {
status: "expired",
};
} else if (errorMessage === "sorry. your account was suspended.") {
details[pat] = {
status: "suspended",
};
} else {
throw err;
}
}
}
const filterPATsByStatus = (status) => {
return Object.keys(details).filter((pat) => details[pat].status === status);
};
const sortedDetails = Object.keys(details)
.sort()
.reduce((obj, key) => {
obj[key] = details[key];
return obj;
}, {});
return {
validPATs: filterPATsByStatus("valid"),
expiredPATs: filterPATsByStatus("expired"),
exhaustedPATs: filterPATsByStatus("exhausted"),
suspendedPATs: filterPATsByStatus("suspended"),
errorPATs: filterPATsByStatus("error"),
details: sortedDetails,
};
};
/**
* Cloud function that returns information about the used PATs.
*
* @param {any} _ The request.
* @param {any} res The response.
* @returns {Promise<void>} The response.
*/
export default async (_, res) => {
res.setHeader("Content-Type", "application/json");
try {
// Add header to prevent abuse.
const PATsInfo = await getPATInfo(uptimeFetcher, {});
if (PATsInfo) {
res.setHeader(
"Cache-Control",
`max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
);
}
res.send(JSON.stringify(PATsInfo, null, 2));
} catch (err) {
// Throw error if something went wrong.
logger.error(err);
res.setHeader("Cache-Control", "no-store");
res.send("Something went wrong: " + err.message);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/api/status/up.js | api/status/up.js | // @ts-check
/**
* @file Contains a simple cloud function that can be used to check if the PATs are still
* functional.
*
* @description This function is currently rate limited to 1 request per 5 minutes.
*/
import { request } from "../../src/common/http.js";
import retryer from "../../src/common/retryer.js";
import { logger } from "../../src/common/log.js";
export const RATE_LIMIT_SECONDS = 60 * 5; // 1 request per 5 minutes
/**
* Simple uptime check fetcher for the PATs.
*
* @param {any} variables Fetcher variables.
* @param {string} token GitHub token.
* @returns {Promise<import('axios').AxiosResponse>} The response.
*/
const uptimeFetcher = (variables, token) => {
return request(
{
query: `
query {
rateLimit {
remaining
}
}
`,
variables,
},
{
Authorization: `bearer ${token}`,
},
);
};
/**
* @typedef {{
* schemaVersion: number;
* label: string;
* message: "up" | "down";
* color: "brightgreen" | "red";
* isError: boolean
* }} ShieldsResponse Shields.io response object.
*/
/**
* Creates Json response that can be used for shields.io dynamic card generation.
*
* @param {boolean} up Whether the PATs are up or not.
* @returns {ShieldsResponse} Dynamic shields.io JSON response object.
*
* @see https://shields.io/endpoint.
*/
const shieldsUptimeBadge = (up) => {
const schemaVersion = 1;
const isError = true;
const label = "Public Instance";
const message = up ? "up" : "down";
const color = up ? "brightgreen" : "red";
return {
schemaVersion,
label,
message,
color,
isError,
};
};
/**
* Cloud function that returns whether the PATs are still functional.
*
* @param {any} req The request.
* @param {any} res The response.
* @returns {Promise<void>} Nothing.
*/
export default async (req, res) => {
let { type } = req.query;
type = type ? type.toLowerCase() : "boolean";
res.setHeader("Content-Type", "application/json");
try {
let PATsValid = true;
try {
await retryer(uptimeFetcher, {});
} catch (err) {
// Resolve eslint no-unused-vars
err;
PATsValid = false;
}
if (PATsValid) {
res.setHeader(
"Cache-Control",
`max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
);
} else {
res.setHeader("Cache-Control", "no-store");
}
switch (type) {
case "shields":
res.send(shieldsUptimeBadge(PATsValid));
break;
case "json":
res.send({ up: PATsValid });
break;
default:
res.send(PATsValid);
break;
}
} catch (err) {
// Return fail boolean if something went wrong.
logger.error(err);
res.setHeader("Cache-Control", "no-store");
res.send("Something went wrong: " + err.message);
}
};
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
anuraghazra/github-readme-stats | https://github.com/anuraghazra/github-readme-stats/blob/8108ba1417faaad7182399e01dd724777adc63e5/themes/index.js | themes/index.js | export const themes = {
default: {
title_color: "2f80ed",
icon_color: "4c71f2",
text_color: "434d58",
bg_color: "fffefe",
border_color: "e4e2e2",
},
default_repocard: {
title_color: "2f80ed",
icon_color: "586069", // icon color is different
text_color: "434d58",
bg_color: "fffefe",
},
transparent: {
title_color: "006AFF",
icon_color: "0579C3",
text_color: "417E87",
bg_color: "ffffff00",
},
shadow_red: {
title_color: "9A0000",
text_color: "444",
icon_color: "4F0000",
border_color: "4F0000",
bg_color: "ffffff00",
},
shadow_green: {
title_color: "007A00",
text_color: "444",
icon_color: "003D00",
border_color: "003D00",
bg_color: "ffffff00",
},
shadow_blue: {
title_color: "00779A",
text_color: "444",
icon_color: "004450",
border_color: "004490",
bg_color: "ffffff00",
},
dark: {
title_color: "fff",
icon_color: "79ff97",
text_color: "9f9f9f",
bg_color: "151515",
},
radical: {
title_color: "fe428e",
icon_color: "f8d847",
text_color: "a9fef7",
bg_color: "141321",
},
merko: {
title_color: "abd200",
icon_color: "b7d364",
text_color: "68b587",
bg_color: "0a0f0b",
},
gruvbox: {
title_color: "fabd2f",
icon_color: "fe8019",
text_color: "8ec07c",
bg_color: "282828",
},
gruvbox_light: {
title_color: "b57614",
icon_color: "af3a03",
text_color: "427b58",
bg_color: "fbf1c7",
},
tokyonight: {
title_color: "70a5fd",
icon_color: "bf91f3",
text_color: "38bdae",
bg_color: "1a1b27",
},
onedark: {
title_color: "e4bf7a",
icon_color: "8eb573",
text_color: "df6d74",
bg_color: "282c34",
},
cobalt: {
title_color: "e683d9",
icon_color: "0480ef",
text_color: "75eeb2",
bg_color: "193549",
},
synthwave: {
title_color: "e2e9ec",
icon_color: "ef8539",
text_color: "e5289e",
bg_color: "2b213a",
},
highcontrast: {
title_color: "e7f216",
icon_color: "00ffff",
text_color: "fff",
bg_color: "000",
},
dracula: {
title_color: "ff6e96",
icon_color: "79dafa",
text_color: "f8f8f2",
bg_color: "282a36",
},
prussian: {
title_color: "bddfff",
icon_color: "38a0ff",
text_color: "6e93b5",
bg_color: "172f45",
},
monokai: {
title_color: "eb1f6a",
icon_color: "e28905",
text_color: "f1f1eb",
bg_color: "272822",
},
vue: {
title_color: "41b883",
icon_color: "41b883",
text_color: "273849",
bg_color: "fffefe",
},
"vue-dark": {
title_color: "41b883",
icon_color: "41b883",
text_color: "fffefe",
bg_color: "273849",
},
"shades-of-purple": {
title_color: "fad000",
icon_color: "b362ff",
text_color: "a599e9",
bg_color: "2d2b55",
},
nightowl: {
title_color: "c792ea",
icon_color: "ffeb95",
text_color: "7fdbca",
bg_color: "011627",
},
buefy: {
title_color: "7957d5",
icon_color: "ff3860",
text_color: "363636",
bg_color: "ffffff",
},
"blue-green": {
title_color: "2f97c1",
icon_color: "f5b700",
text_color: "0cf574",
bg_color: "040f0f",
},
algolia: {
title_color: "00AEFF",
icon_color: "2DDE98",
text_color: "FFFFFF",
bg_color: "050F2C",
},
"great-gatsby": {
title_color: "ffa726",
icon_color: "ffb74d",
text_color: "ffd95b",
bg_color: "000000",
},
darcula: {
title_color: "BA5F17",
icon_color: "84628F",
text_color: "BEBEBE",
bg_color: "242424",
},
bear: {
title_color: "e03c8a",
icon_color: "00AEFF",
text_color: "bcb28d",
bg_color: "1f2023",
},
"solarized-dark": {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "002b36",
},
"solarized-light": {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "fdf6e3",
},
"chartreuse-dark": {
title_color: "7fff00",
icon_color: "00AEFF",
text_color: "fff",
bg_color: "000",
},
nord: {
title_color: "81a1c1",
text_color: "d8dee9",
icon_color: "88c0d0",
bg_color: "2e3440",
},
gotham: {
title_color: "2aa889",
icon_color: "599cab",
text_color: "99d1ce",
bg_color: "0c1014",
},
"material-palenight": {
title_color: "c792ea",
icon_color: "89ddff",
text_color: "a6accd",
bg_color: "292d3e",
},
graywhite: {
title_color: "24292e",
icon_color: "24292e",
text_color: "24292e",
bg_color: "ffffff",
},
"vision-friendly-dark": {
title_color: "ffb000",
icon_color: "785ef0",
text_color: "ffffff",
bg_color: "000000",
},
"ayu-mirage": {
title_color: "f4cd7c",
icon_color: "73d0ff",
text_color: "c7c8c2",
bg_color: "1f2430",
},
"midnight-purple": {
title_color: "9745f5",
icon_color: "9f4bff",
text_color: "ffffff",
bg_color: "000000",
},
calm: {
title_color: "e07a5f",
icon_color: "edae49",
text_color: "ebcfb2",
bg_color: "373f51",
},
"flag-india": {
title_color: "ff8f1c",
icon_color: "250E62",
text_color: "509E2F",
bg_color: "ffffff",
},
omni: {
title_color: "FF79C6",
icon_color: "e7de79",
text_color: "E1E1E6",
bg_color: "191622",
},
react: {
title_color: "61dafb",
icon_color: "61dafb",
text_color: "ffffff",
bg_color: "20232a",
},
jolly: {
title_color: "ff64da",
icon_color: "a960ff",
text_color: "ffffff",
bg_color: "291B3E",
},
maroongold: {
title_color: "F7EF8A",
icon_color: "F7EF8A",
text_color: "E0AA3E",
bg_color: "260000",
},
yeblu: {
title_color: "ffff00",
icon_color: "ffff00",
text_color: "ffffff",
bg_color: "002046",
},
blueberry: {
title_color: "82aaff",
icon_color: "89ddff",
text_color: "27e8a7",
bg_color: "242938",
},
slateorange: {
title_color: "faa627",
icon_color: "faa627",
text_color: "ffffff",
bg_color: "36393f",
},
kacho_ga: {
title_color: "bf4a3f",
icon_color: "a64833",
text_color: "d9c8a9",
bg_color: "402b23",
},
outrun: {
title_color: "ffcc00",
icon_color: "ff1aff",
text_color: "8080ff",
bg_color: "141439",
},
ocean_dark: {
title_color: "8957B2",
icon_color: "FFFFFF",
text_color: "92D534",
bg_color: "151A28",
},
city_lights: {
title_color: "5D8CB3",
icon_color: "4798FF",
text_color: "718CA1",
bg_color: "1D252C",
},
github_dark: {
title_color: "58A6FF",
icon_color: "1F6FEB",
text_color: "C3D1D9",
bg_color: "0D1117",
},
github_dark_dimmed: {
title_color: "539bf5",
icon_color: "539bf5",
text_color: "ADBAC7",
bg_color: "24292F",
border_color: "373E47",
},
discord_old_blurple: {
title_color: "7289DA",
icon_color: "7289DA",
text_color: "FFFFFF",
bg_color: "2C2F33",
},
aura_dark: {
title_color: "ff7372",
icon_color: "6cffd0",
text_color: "dbdbdb",
bg_color: "252334",
},
panda: {
title_color: "19f9d899",
icon_color: "19f9d899",
text_color: "FF75B5",
bg_color: "31353a",
},
noctis_minimus: {
title_color: "d3b692",
icon_color: "72b7c0",
text_color: "c5cdd3",
bg_color: "1b2932",
},
cobalt2: {
title_color: "ffc600",
icon_color: "ffffff",
text_color: "0088ff",
bg_color: "193549",
},
swift: {
title_color: "000000",
icon_color: "f05237",
text_color: "000000",
bg_color: "f7f7f7",
},
aura: {
title_color: "a277ff",
icon_color: "ffca85",
text_color: "61ffca",
bg_color: "15141b",
},
apprentice: {
title_color: "ffffff",
icon_color: "ffffaf",
text_color: "bcbcbc",
bg_color: "262626",
},
moltack: {
title_color: "86092C",
icon_color: "86092C",
text_color: "574038",
bg_color: "F5E1C0",
},
codeSTACKr: {
title_color: "ff652f",
icon_color: "FFE400",
text_color: "ffffff",
bg_color: "09131B",
border_color: "0c1a25",
},
rose_pine: {
title_color: "9ccfd8",
icon_color: "ebbcba",
text_color: "e0def4",
bg_color: "191724",
},
catppuccin_latte: {
title_color: "137980",
icon_color: "8839ef",
text_color: "4c4f69",
bg_color: "eff1f5",
},
catppuccin_mocha: {
title_color: "94e2d5",
icon_color: "cba6f7",
text_color: "cdd6f4",
bg_color: "1e1e2e",
},
date_night: {
title_color: "DA7885",
text_color: "E1B2A2",
icon_color: "BB8470",
border_color: "170F0C",
bg_color: "170F0C",
},
one_dark_pro: {
title_color: "61AFEF",
text_color: "E5C06E",
icon_color: "C678DD",
border_color: "3B4048",
bg_color: "23272E",
},
rose: {
title_color: "8d192b",
text_color: "862931",
icon_color: "B71F36",
border_color: "e9d8d4",
bg_color: "e9d8d4",
},
holi: {
title_color: "5FABEE",
text_color: "D6E7FF",
icon_color: "5FABEE",
border_color: "85A4C0",
bg_color: "030314",
},
neon: {
title_color: "00EAD3",
text_color: "FF449F",
icon_color: "00EAD3",
border_color: "ffffff",
bg_color: "000000",
},
blue_navy: {
title_color: "82AAFF",
text_color: "82AAFF",
icon_color: "82AAFF",
border_color: "ffffff",
bg_color: "000000",
},
calm_pink: {
title_color: "e07a5f",
text_color: "edae49",
icon_color: "ebcfb2",
border_color: "e1bc29",
bg_color: "2b2d40",
},
ambient_gradient: {
title_color: "ffffff",
text_color: "ffffff",
icon_color: "ffffff",
bg_color: "35,4158d0,c850c0,ffcc70",
},
};
export default themes;
| javascript | MIT | 8108ba1417faaad7182399e01dd724777adc63e5 | 2026-01-04T14:56:49.628708Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/index.js | index.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
module.exports = require('./lib/express');
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/benchmarks/middleware.js | benchmarks/middleware.js |
var express = require('..');
var app = express();
// number of middleware
var n = parseInt(process.env.MW || '1', 10);
console.log(' %s middleware', n);
while (n--) {
app.use(function(req, res, next){
next();
});
}
app.use(function(req, res){
res.send('Hello World')
});
app.listen(3333);
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.path.js | test/req.path.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.path', function(){
it('should return the parsed pathname', function(done){
var app = express();
app.use(function(req, res){
res.end(req.path);
});
request(app)
.get('/login?redirect=/post/1/comments')
.expect('/login', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/regression.js | test/regression.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('throw after .end()', function(){
it('should fail gracefully', function(done){
var app = express();
app.get('/', function(req, res){
res.end('yay');
throw new Error('boom');
});
request(app)
.get('/')
.expect('yay')
.expect(200, done);
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.location.js | test/res.location.js | 'use strict'
var express = require('../')
, request = require('supertest')
, assert = require('node:assert')
, url = require('node:url');
describe('res', function(){
describe('.location(url)', function(){
it('should set the header', function(done){
var app = express();
app.use(function(req, res){
res.location('http://google.com/').end();
});
request(app)
.get('/')
.expect('Location', 'http://google.com/')
.expect(200, done)
})
it('should preserve trailing slashes when not present', function(done){
var app = express();
app.use(function(req, res){
res.location('http://google.com').end();
});
request(app)
.get('/')
.expect('Location', 'http://google.com')
.expect(200, done)
})
it('should encode "url"', function (done) {
var app = express()
app.use(function (req, res) {
res.location('https://google.com?q=\u2603 §10').end()
})
request(app)
.get('/')
.expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710')
.expect(200, done)
})
it('should encode data uri1', function (done) {
var app = express()
app.use(function (req, res) {
res.location('data:text/javascript,export default () => { }').end();
});
request(app)
.get('/')
.expect('Location', 'data:text/javascript,export%20default%20()%20=%3E%20%7B%20%7D')
.expect(200, done)
})
it('should encode data uri2', function (done) {
var app = express()
app.use(function (req, res) {
res.location('data:text/javascript,export default () => { }').end();
});
request(app)
.get('/')
.expect('Location', 'data:text/javascript,export%20default%20()%20=%3E%20%7B%20%7D')
.expect(200, done)
})
it('should consistently handle non-string input: boolean', function (done) {
var app = express()
app.use(function (req, res) {
res.location(true).end();
});
request(app)
.get('/')
.expect('Location', 'true')
.expect(200, done)
});
it('should consistently handle non-string inputs: object', function (done) {
var app = express()
app.use(function (req, res) {
res.location({}).end();
});
request(app)
.get('/')
.expect('Location', '[object%20Object]')
.expect(200, done)
});
it('should consistently handle non-string inputs: array', function (done) {
var app = express()
app.use(function (req, res) {
res.location([]).end();
});
request(app)
.get('/')
.expect('Location', '')
.expect(200, done)
});
it('should consistently handle empty string input', function (done) {
var app = express()
app.use(function (req, res) {
res.location('').end();
});
request(app)
.get('/')
.expect('Location', '')
.expect(200, done)
});
if (typeof URL !== 'undefined') {
it('should accept an instance of URL', function (done) {
var app = express();
app.use(function(req, res){
res.location(new URL('http://google.com/')).end();
});
request(app)
.get('/')
.expect('Location', 'http://google.com/')
.expect(200, done);
});
}
})
describe('location header encoding', function() {
function createRedirectServerForDomain (domain) {
var app = express();
app.use(function (req, res) {
var host = url.parse(req.query.q, false, true).host;
// This is here to show a basic check one might do which
// would pass but then the location header would still be bad
if (host !== domain) {
res.status(400).end('Bad host: ' + host + ' !== ' + domain);
}
res.location(req.query.q).end();
});
return app;
}
function testRequestedRedirect (app, inputUrl, expected, expectedHost, done) {
return request(app)
// Encode uri because old supertest does not and is required
// to test older node versions. New supertest doesn't re-encode
// so this works in both.
.get('/?q=' + encodeURIComponent(inputUrl))
.expect('') // No body.
.expect(200)
.expect('Location', expected)
.end(function (err, res) {
if (err) {
console.log('headers:', res.headers)
console.error('error', res.error, err);
return done(err, res);
}
// Parse the hosts from the input URL and the Location header
var inputHost = url.parse(inputUrl, false, true).host;
var locationHost = url.parse(res.headers['location'], false, true).host;
assert.strictEqual(locationHost, expectedHost);
// Assert that the hosts are the same
if (inputHost !== locationHost) {
return done(new Error('Hosts do not match: ' + inputHost + " !== " + locationHost));
}
return done(null, res);
});
}
it('should not touch already-encoded sequences in "url"', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'https://google.com?q=%A710',
'https://google.com?q=%A710',
'google.com',
done
);
});
it('should consistently handle relative urls', function (done) {
var app = createRedirectServerForDomain(null);
testRequestedRedirect(
app,
'/foo/bar',
'/foo/bar',
null,
done
);
});
it('should not encode urls in such a way that they can bypass redirect allow lists', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'http://google.com\\@apple.com',
'http://google.com\\@apple.com',
'google.com',
done
);
});
it('should not be case sensitive', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'HTTP://google.com\\@apple.com',
'HTTP://google.com\\@apple.com',
'google.com',
done
);
});
it('should work with https', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'https://google.com\\@apple.com',
'https://google.com\\@apple.com',
'google.com',
done
);
});
it('should correctly encode schemaless paths', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'//google.com\\@apple.com/',
'//google.com\\@apple.com/',
'google.com',
done
);
});
it('should keep backslashes in the path', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'https://google.com/foo\\bar\\baz',
'https://google.com/foo\\bar\\baz',
'google.com',
done
);
});
it('should escape header splitting for old node versions', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'http://google.com\\@apple.com/%0d%0afoo:%20bar',
'http://google.com\\@apple.com/%0d%0afoo:%20bar',
'google.com',
done
);
});
it('should encode unicode correctly', function (done) {
var app = createRedirectServerForDomain(null);
testRequestedRedirect(
app,
'/%e2%98%83',
'/%e2%98%83',
null,
done
);
});
it('should encode unicode correctly even with a bad host', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'http://google.com\\@apple.com/%e2%98%83',
'http://google.com\\@apple.com/%e2%98%83',
'google.com',
done
);
});
it('should work correctly despite using deprecated url.parse', function (done) {
var app = createRedirectServerForDomain('google.com');
testRequestedRedirect(
app,
'https://google.com\'.bb.com/1.html',
'https://google.com\'.bb.com/1.html',
'google.com',
done
);
});
it('should encode file uri path', function (done) {
var app = createRedirectServerForDomain('');
testRequestedRedirect(
app,
'file:///etc\\passwd',
'file:///etc\\passwd',
'',
done
);
});
});
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.range.js | test/req.range.js | 'use strict'
var express = require('..');
var request = require('supertest')
describe('req', function(){
describe('.range(size)', function(){
it('should return parsed ranges', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(120))
})
request(app)
.get('/')
.set('Range', 'bytes=0-50,51-100')
.expect(200, '[{"start":0,"end":50},{"start":51,"end":100}]', done)
})
it('should cap to the given size', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(75))
})
request(app)
.get('/')
.set('Range', 'bytes=0-100')
.expect(200, '[{"start":0,"end":74}]', done)
})
it('should cap to the given size when open-ended', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(75))
})
request(app)
.get('/')
.set('Range', 'bytes=0-')
.expect(200, '[{"start":0,"end":74}]', done)
})
it('should have a .type', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(120).type)
})
request(app)
.get('/')
.set('Range', 'bytes=0-100')
.expect(200, '"bytes"', done)
})
it('should accept any type', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(120).type)
})
request(app)
.get('/')
.set('Range', 'users=0-2')
.expect(200, '"users"', done)
})
it('should return undefined if no range', function (done) {
var app = express()
app.use(function (req, res) {
res.send(String(req.range(120)))
})
request(app)
.get('/')
.expect(200, 'undefined', done)
})
})
describe('.range(size, options)', function(){
describe('with "combine: true" option', function(){
it('should return combined ranges', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.range(120, {
combine: true
}))
})
request(app)
.get('/')
.set('Range', 'bytes=0-50,51-100')
.expect(200, '[{"start":0,"end":100}]', done)
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.get.js | test/req.get.js | 'use strict'
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
describe('req', function(){
describe('.get(field)', function(){
it('should return the header field value', function(done){
var app = express();
app.use(function(req, res){
assert(req.get('Something-Else') === undefined);
res.end(req.get('Content-Type'));
});
request(app)
.post('/')
.set('Content-Type', 'application/json')
.expect('application/json', done);
})
it('should special-case Referer', function(done){
var app = express();
app.use(function(req, res){
res.end(req.get('Referer'));
});
request(app)
.post('/')
.set('Referrer', 'http://foobar.com')
.expect('http://foobar.com', done);
})
it('should throw missing header name', function (done) {
var app = express()
app.use(function (req, res) {
res.end(req.get())
})
request(app)
.get('/')
.expect(500, /TypeError: name argument is required to req.get/, done)
})
it('should throw for non-string header name', function (done) {
var app = express()
app.use(function (req, res) {
res.end(req.get(42))
})
request(app)
.get('/')
.expect(500, /TypeError: name must be a string to req.get/, done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.engine.js | test/app.engine.js | 'use strict'
var assert = require('node:assert')
var express = require('../')
, fs = require('node:fs');
var path = require('node:path')
function render(path, options, fn) {
fs.readFile(path, 'utf8', function(err, str){
if (err) return fn(err);
str = str.replace('{{user.name}}', options.user.name);
fn(null, str);
});
}
describe('app', function(){
describe('.engine(ext, fn)', function(){
it('should map a template engine', function(done){
var app = express();
app.set('views', path.join(__dirname, 'fixtures'))
app.engine('.html', render);
app.locals.user = { name: 'tobi' };
app.render('user.html', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should throw when the callback is missing', function(){
var app = express();
assert.throws(function () {
app.engine('.html', null);
}, /callback function required/)
})
it('should work without leading "."', function(done){
var app = express();
app.set('views', path.join(__dirname, 'fixtures'))
app.engine('html', render);
app.locals.user = { name: 'tobi' };
app.render('user.html', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should work "view engine" setting', function(done){
var app = express();
app.set('views', path.join(__dirname, 'fixtures'))
app.engine('html', render);
app.set('view engine', 'html');
app.locals.user = { name: 'tobi' };
app.render('user', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should work "view engine" with leading "."', function(done){
var app = express();
app.set('views', path.join(__dirname, 'fixtures'))
app.engine('.html', render);
app.set('view engine', '.html');
app.locals.user = { name: 'tobi' };
app.render('user', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.fresh.js | test/req.fresh.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.fresh', function(){
it('should return true when the resource is not modified', function(done){
var app = express();
var etag = '"12345"';
app.use(function(req, res){
res.set('ETag', etag);
res.send(req.fresh);
});
request(app)
.get('/')
.set('If-None-Match', etag)
.expect(304, done);
})
it('should return false when the resource is modified', function(done){
var app = express();
app.use(function(req, res){
res.set('ETag', '"123"');
res.send(req.fresh);
});
request(app)
.get('/')
.set('If-None-Match', '"12345"')
.expect(200, 'false', done);
})
it('should return false without response headers', function(done){
var app = express();
app.disable('x-powered-by')
app.use(function(req, res){
res.send(req.fresh);
});
request(app)
.get('/')
.expect(200, 'false', done);
})
it('should ignore "If-Modified-Since" when "If-None-Match" is present', function(done) {
var app = express();
const etag = '"FooBar"'
const now = Date.now()
app.disable('x-powered-by')
app.use(function(req, res) {
res.set('Etag', etag)
res.set('Last-Modified', new Date(now).toUTCString())
res.send(req.fresh);
});
request(app)
.get('/')
.set('If-Modified-Since', new Date(now - 1000).toUTCString)
.set('If-None-Match', etag)
.expect(304, done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.subdomains.js | test/req.subdomains.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.subdomains', function(){
describe('when present', function(){
it('should return an array', function(done){
var app = express();
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'tobi.ferrets.example.com')
.expect(200, ['ferrets', 'tobi'], done);
})
it('should work with IPv4 address', function(done){
var app = express();
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', '127.0.0.1')
.expect(200, [], done);
})
it('should work with IPv6 address', function(done){
var app = express();
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', '[::1]')
.expect(200, [], done);
})
})
describe('otherwise', function(){
it('should return an empty array', function(done){
var app = express();
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'example.com')
.expect(200, [], done);
})
})
describe('with no host', function(){
it('should return an empty array', function(done){
var app = express();
app.use(function(req, res){
req.headers.host = null;
res.send(req.subdomains);
});
request(app)
.get('/')
.expect(200, [], done);
})
})
describe('with trusted X-Forwarded-Host', function () {
it('should return an array', function (done) {
var app = express();
app.set('trust proxy', true);
app.use(function (req, res) {
res.send(req.subdomains);
});
request(app)
.get('/')
.set('X-Forwarded-Host', 'tobi.ferrets.example.com')
.expect(200, ['ferrets', 'tobi'], done);
})
})
describe('when subdomain offset is set', function(){
describe('when subdomain offset is zero', function(){
it('should return an array with the whole domain', function(done){
var app = express();
app.set('subdomain offset', 0);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'tobi.ferrets.sub.example.com')
.expect(200, ['com', 'example', 'sub', 'ferrets', 'tobi'], done);
})
it('should return an array with the whole IPv4', function (done) {
var app = express();
app.set('subdomain offset', 0);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', '127.0.0.1')
.expect(200, ['127.0.0.1'], done);
})
it('should return an array with the whole IPv6', function (done) {
var app = express();
app.set('subdomain offset', 0);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', '[::1]')
.expect(200, ['[::1]'], done);
})
})
describe('when present', function(){
it('should return an array', function(done){
var app = express();
app.set('subdomain offset', 3);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'tobi.ferrets.sub.example.com')
.expect(200, ['ferrets', 'tobi'], done);
})
})
describe('otherwise', function(){
it('should return an empty array', function(done){
var app = express();
app.set('subdomain offset', 3);
app.use(function(req, res){
res.send(req.subdomains);
});
request(app)
.get('/')
.set('Host', 'sub.example.com')
.expect(200, [], done);
})
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.redirect.js | test/res.redirect.js | 'use strict'
var express = require('..');
var request = require('supertest');
var utils = require('./support/utils');
describe('res', function(){
describe('.redirect(url)', function(){
it('should default to a 302 redirect', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://google.com');
});
request(app)
.get('/')
.expect('location', 'http://google.com')
.expect(302, done)
})
it('should encode "url"', function (done) {
var app = express()
app.use(function (req, res) {
res.redirect('https://google.com?q=\u2603 §10')
})
request(app)
.get('/')
.expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710')
.expect(302, done)
})
it('should not touch already-encoded sequences in "url"', function (done) {
var app = express()
app.use(function (req, res) {
res.redirect('https://google.com?q=%A710')
})
request(app)
.get('/')
.expect('Location', 'https://google.com?q=%A710')
.expect(302, done)
})
})
describe('.redirect(status, url)', function(){
it('should set the response status', function(done){
var app = express();
app.use(function(req, res){
res.redirect(303, 'http://google.com');
});
request(app)
.get('/')
.expect('Location', 'http://google.com')
.expect(303, done)
})
})
describe('when the request method is HEAD', function(){
it('should ignore the body', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://google.com');
});
request(app)
.head('/')
.expect(302)
.expect('Location', 'http://google.com')
.expect(utils.shouldNotHaveBody())
.end(done)
})
})
describe('when accepting html', function(){
it('should respond with html', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://google.com');
});
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', /html/)
.expect('Location', 'http://google.com')
.expect(302, '<p>Found. Redirecting to http://google.com</p>', done)
})
it('should escape the url', function(done){
var app = express();
app.use(function(req, res){
res.redirect('<la\'me>');
});
request(app)
.get('/')
.set('Host', 'http://example.com')
.set('Accept', 'text/html')
.expect('Content-Type', /html/)
.expect('Location', '%3Cla\'me%3E')
.expect(302, '<p>Found. Redirecting to %3Cla'me%3E</p>', done)
})
it('should not render evil javascript links in anchor href (prevent XSS)', function(done){
var app = express();
var xss = 'javascript:eval(document.body.innerHTML=`<p>XSS</p>`);';
var encodedXss = 'javascript:eval(document.body.innerHTML=%60%3Cp%3EXSS%3C/p%3E%60);';
app.use(function(req, res){
res.redirect(xss);
});
request(app)
.get('/')
.set('Host', 'http://example.com')
.set('Accept', 'text/html')
.expect('Content-Type', /html/)
.expect('Location', encodedXss)
.expect(302, '<p>Found. Redirecting to ' + encodedXss +'</p>', done);
});
it('should include the redirect type', function(done){
var app = express();
app.use(function(req, res){
res.redirect(301, 'http://google.com');
});
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', /html/)
.expect('Location', 'http://google.com')
.expect(301, '<p>Moved Permanently. Redirecting to http://google.com</p>', done);
})
})
describe('when accepting text', function(){
it('should respond with text', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://google.com');
});
request(app)
.get('/')
.set('Accept', 'text/plain, */*')
.expect('Content-Type', /plain/)
.expect('Location', 'http://google.com')
.expect(302, 'Found. Redirecting to http://google.com', done)
})
it('should encode the url', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://example.com/?param=<script>alert("hax");</script>');
});
request(app)
.get('/')
.set('Host', 'http://example.com')
.set('Accept', 'text/plain, */*')
.expect('Content-Type', /plain/)
.expect('Location', 'http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E')
.expect(302, 'Found. Redirecting to http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', done)
})
it('should include the redirect type', function(done){
var app = express();
app.use(function(req, res){
res.redirect(301, 'http://google.com');
});
request(app)
.get('/')
.set('Accept', 'text/plain, */*')
.expect('Content-Type', /plain/)
.expect('Location', 'http://google.com')
.expect(301, 'Moved Permanently. Redirecting to http://google.com', done);
})
})
describe('when accepting neither text or html', function(){
it('should respond with an empty body', function(done){
var app = express();
app.use(function(req, res){
res.redirect('http://google.com');
});
request(app)
.get('/')
.set('Accept', 'application/octet-stream')
.expect(302)
.expect('location', 'http://google.com')
.expect('content-length', '0')
.expect(utils.shouldNotHaveHeader('Content-Type'))
.expect(utils.shouldNotHaveBody())
.end(done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.acceptsCharsets.js | test/req.acceptsCharsets.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.acceptsCharsets(type)', function(){
describe('when Accept-Charset is not present', function(){
it('should return true', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no');
});
request(app)
.get('/')
.expect('yes', done);
})
})
describe('when Accept-Charset is present', function () {
it('should return true', function (done) {
var app = express();
app.use(function(req, res, next){
res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept-Charset', 'foo, bar, utf-8')
.expect('yes', done);
})
it('should return false otherwise', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept-Charset', 'foo, bar')
.expect('no', done);
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.is.js | test/req.is.js | 'use strict'
var express = require('..')
var request = require('supertest')
describe('req.is()', function () {
describe('when given a mime type', function () {
it('should return the type when matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/json'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, '"application/json"', done)
})
it('should return false when not matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('image/jpeg'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, 'false', done)
})
it('should ignore charset', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/json'))
})
request(app)
.post('/')
.type('application/json; charset=UTF-8')
.send('{}')
.expect(200, '"application/json"', done)
})
})
describe('when content-type is not present', function(){
it('should return false', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/json'))
})
request(app)
.post('/')
.send('{}')
.expect(200, 'false', done)
})
})
describe('when given an extension', function(){
it('should lookup the mime type', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('json'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, '"json"', done)
})
})
describe('when given */subtype', function(){
it('should return the full type when matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('*/json'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, '"application/json"', done)
})
it('should return false when not matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('*/html'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, 'false', done)
})
it('should ignore charset', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('*/json'))
})
request(app)
.post('/')
.type('application/json; charset=UTF-8')
.send('{}')
.expect(200, '"application/json"', done)
})
})
describe('when given type/*', function(){
it('should return the full type when matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/*'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, '"application/json"', done)
})
it('should return false when not matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('text/*'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, 'false', done)
})
it('should ignore charset', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/*'))
})
request(app)
.post('/')
.type('application/json; charset=UTF-8')
.send('{}')
.expect(200, '"application/json"', done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.render.js | test/res.render.js | 'use strict'
var express = require('..');
var path = require('node:path')
var request = require('supertest');
var tmpl = require('./support/tmpl');
describe('res', function(){
describe('.render(name)', function(){
it('should support absolute paths', function(done){
var app = createApp();
app.locals.user = { name: 'tobi' };
app.use(function(req, res){
res.render(path.join(__dirname, 'fixtures', 'user.tmpl'))
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should support absolute paths with "view engine"', function(done){
var app = createApp();
app.locals.user = { name: 'tobi' };
app.set('view engine', 'tmpl');
app.use(function(req, res){
res.render(path.join(__dirname, 'fixtures', 'user'))
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should error without "view engine" set and file extension to a non-engine module', function (done) {
var app = createApp()
app.locals.user = { name: 'tobi' }
app.use(function (req, res) {
res.render(path.join(__dirname, 'fixtures', 'broken.send'))
})
request(app)
.get('/')
.expect(500, /does not provide a view engine/, done)
})
it('should error without "view engine" set and no file extension', function (done) {
var app = createApp();
app.locals.user = { name: 'tobi' };
app.use(function(req, res){
res.render(path.join(__dirname, 'fixtures', 'user'))
});
request(app)
.get('/')
.expect(500, /No default engine was specified/, done);
})
it('should expose app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.use(function(req, res){
res.render('user.tmpl');
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should expose app.locals with `name` property', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.name = 'tobi';
app.use(function(req, res){
res.render('name.tmpl');
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should support index.<engine>', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.set('view engine', 'tmpl');
app.use(function(req, res){
res.render('blog/post');
});
request(app)
.get('/')
.expect('<h1>blog post</h1>', done);
})
describe('when an error occurs', function(){
it('should next(err)', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
res.render('user.tmpl');
});
app.use(function(err, req, res, next){
res.status(500).send('got error: ' + err.name)
});
request(app)
.get('/')
.expect(500, 'got error: RenderError', done)
})
})
describe('when "view engine" is given', function(){
it('should render the template', function(done){
var app = createApp();
app.set('view engine', 'tmpl');
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
res.render('email');
});
request(app)
.get('/')
.expect('<p>This is an email</p>', done);
})
})
describe('when "views" is given', function(){
it('should lookup the file in the path', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures', 'default_layout'))
app.use(function(req, res){
res.render('user.tmpl', { user: { name: 'tobi' } });
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
describe('when array of paths', function(){
it('should lookup the file in the path', function(done){
var app = createApp();
var views = [
path.join(__dirname, 'fixtures', 'local_layout'),
path.join(__dirname, 'fixtures', 'default_layout')
]
app.set('views', views);
app.use(function(req, res){
res.render('user.tmpl', { user: { name: 'tobi' } });
});
request(app)
.get('/')
.expect('<span>tobi</span>', done);
})
it('should lookup in later paths until found', function(done){
var app = createApp();
var views = [
path.join(__dirname, 'fixtures', 'local_layout'),
path.join(__dirname, 'fixtures', 'default_layout')
]
app.set('views', views);
app.use(function(req, res){
res.render('name.tmpl', { name: 'tobi' });
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
})
})
})
describe('.render(name, option)', function(){
it('should render the template', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
var user = { name: 'tobi' };
app.use(function(req, res){
res.render('user.tmpl', { user: user });
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should expose app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.use(function(req, res){
res.render('user.tmpl');
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should expose res.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
res.locals.user = { name: 'tobi' };
res.render('user.tmpl');
});
request(app)
.get('/')
.expect('<p>tobi</p>', done);
})
it('should give precedence to res.locals over app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.use(function(req, res){
res.locals.user = { name: 'jane' };
res.render('user.tmpl', {});
});
request(app)
.get('/')
.expect('<p>jane</p>', done);
})
it('should give precedence to res.render() locals over res.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
var jane = { name: 'jane' };
app.use(function(req, res){
res.locals.user = { name: 'tobi' };
res.render('user.tmpl', { user: jane });
});
request(app)
.get('/')
.expect('<p>jane</p>', done);
})
it('should give precedence to res.render() locals over app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
var jane = { name: 'jane' };
app.use(function(req, res){
res.render('user.tmpl', { user: jane });
});
request(app)
.get('/')
.expect('<p>jane</p>', done);
})
})
describe('.render(name, options, fn)', function(){
it('should pass the resulting string', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
var tobi = { name: 'tobi' };
res.render('user.tmpl', { user: tobi }, function (err, html) {
html = html.replace('tobi', 'loki');
res.end(html);
});
});
request(app)
.get('/')
.expect('<p>loki</p>', done);
})
})
describe('.render(name, fn)', function(){
it('should pass the resulting string', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
res.locals.user = { name: 'tobi' };
res.render('user.tmpl', function (err, html) {
html = html.replace('tobi', 'loki');
res.end(html);
});
});
request(app)
.get('/')
.expect('<p>loki</p>', done);
})
describe('when an error occurs', function(){
it('should pass it to the callback', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.use(function(req, res){
res.render('user.tmpl', function (err) {
if (err) {
res.status(500).send('got error: ' + err.name)
}
});
});
request(app)
.get('/')
.expect(500, 'got error: RenderError', done)
})
})
})
})
function createApp() {
var app = express();
app.engine('.tmpl', tmpl);
return app;
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.type.js | test/res.type.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('res', function(){
describe('.type(str)', function(){
it('should set the Content-Type based on a filename', function(done){
var app = express();
app.use(function(req, res){
res.type('foo.js').end('var name = "tj";');
});
request(app)
.get('/')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.end(done)
})
it('should default to application/octet-stream', function(done){
var app = express();
app.use(function(req, res){
res.type('rawr').end('var name = "tj";');
});
request(app)
.get('/')
.expect('Content-Type', 'application/octet-stream', done);
})
it('should set the Content-Type with type/subtype', function(done){
var app = express();
app.use(function(req, res){
res.type('application/vnd.amazon.ebook')
.end('var name = "tj";');
});
request(app)
.get('/')
.expect('Content-Type', 'application/vnd.amazon.ebook', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.request.js | test/app.request.js | 'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.request', function(){
it('should extend the request prototype', function(done){
var app = express();
app.request.querystring = function(){
return require('node:url').parse(this.url).query;
};
app.use(function(req, res){
res.end(req.querystring());
});
request(app)
.get('/foo?name=tobi')
.expect('name=tobi', done);
})
it('should only extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has no method)/, cb)
})
it('should inherit to sub apps', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app1)
.get('/sub')
.expect(200, 'tobi', cb)
})
it('should allow sub app to override', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app2.request.foobar = function () {
return 'loki'
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app1)
.get('/sub')
.expect(200, 'loki', cb)
})
it('should not pollute parent app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app2.request.foobar = function () {
return 'loki'
}
app1.use('/sub', app2)
app1.get('/sub/foo', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/sub')
.expect(200, 'loki', cb)
request(app1)
.get('/sub/foo')
.expect(200, 'tobi', cb)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/Route.js | test/Route.js | 'use strict'
var after = require('after');
var assert = require('node:assert')
var express = require('../')
, Route = express.Route
, methods = require('../lib/utils').methods
describe('Route', function(){
it('should work without handlers', function(done) {
var req = { method: 'GET', url: '/' }
var route = new Route('/foo')
route.dispatch(req, {}, done)
})
it('should not stack overflow with a large sync stack', function (done) {
this.timeout(5000) // long-running test
var req = { method: 'GET', url: '/' }
var route = new Route('/foo')
route.get(function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
route.all(function (req, res, next) {
req.counter++
next()
})
}
route.get(function (req, res, next) {
req.called = true
next()
})
route.dispatch(req, {}, function (err) {
if (err) return done(err)
assert.ok(req.called)
assert.strictEqual(req.counter, 6000)
done()
})
})
describe('.all', function(){
it('should add handler', function(done){
var req = { method: 'GET', url: '/' };
var route = new Route('/foo');
route.all(function(req, res, next) {
req.called = true;
next();
});
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.ok(req.called)
done();
});
})
it('should handle VERBS', function(done) {
var count = 0;
var route = new Route('/foo');
var cb = after(methods.length, function (err) {
if (err) return done(err);
assert.strictEqual(count, methods.length)
done();
});
route.all(function(req, res, next) {
count++;
next();
});
methods.forEach(function testMethod(method) {
var req = { method: method, url: '/' };
route.dispatch(req, {}, cb);
});
})
it('should stack', function(done) {
var req = { count: 0, method: 'GET', url: '/' };
var route = new Route('/foo');
route.all(function(req, res, next) {
req.count++;
next();
});
route.all(function(req, res, next) {
req.count++;
next();
});
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.strictEqual(req.count, 2)
done();
});
})
})
describe('.VERB', function(){
it('should support .get', function(done){
var req = { method: 'GET', url: '/' };
var route = new Route('');
route.get(function(req, res, next) {
req.called = true;
next();
})
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.ok(req.called)
done();
});
})
it('should limit to just .VERB', function(done){
var req = { method: 'POST', url: '/' };
var route = new Route('');
route.get(function () {
throw new Error('not me!');
})
route.post(function(req, res, next) {
req.called = true;
next();
})
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.ok(req.called)
done();
});
})
it('should allow fallthrough', function(done){
var req = { order: '', method: 'GET', url: '/' };
var route = new Route('');
route.get(function(req, res, next) {
req.order += 'a';
next();
})
route.all(function(req, res, next) {
req.order += 'b';
next();
});
route.get(function(req, res, next) {
req.order += 'c';
next();
})
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.strictEqual(req.order, 'abc')
done();
});
})
})
describe('errors', function(){
it('should handle errors via arity 4 functions', function(done){
var req = { order: '', method: 'GET', url: '/' };
var route = new Route('');
route.all(function(req, res, next){
next(new Error('foobar'));
});
route.all(function(req, res, next){
req.order += '0';
next();
});
route.all(function(err, req, res, next){
req.order += 'a';
next(err);
});
route.dispatch(req, {}, function (err) {
assert.ok(err)
assert.strictEqual(err.message, 'foobar')
assert.strictEqual(req.order, 'a')
done();
});
})
it('should handle throw', function(done) {
var req = { order: '', method: 'GET', url: '/' };
var route = new Route('');
route.all(function () {
throw new Error('foobar');
});
route.all(function(req, res, next){
req.order += '0';
next();
});
route.all(function(err, req, res, next){
req.order += 'a';
next(err);
});
route.dispatch(req, {}, function (err) {
assert.ok(err)
assert.strictEqual(err.message, 'foobar')
assert.strictEqual(req.order, 'a')
done();
});
});
it('should handle throwing inside error handlers', function(done) {
var req = { method: 'GET', url: '/' };
var route = new Route('');
route.get(function () {
throw new Error('boom!');
});
route.get(function(err, req, res, next){
throw new Error('oops');
});
route.get(function(err, req, res, next){
req.message = err.message;
next();
});
route.dispatch(req, {}, function (err) {
if (err) return done(err);
assert.strictEqual(req.message, 'oops')
done();
});
});
it('should handle throw in .all', function(done) {
var req = { method: 'GET', url: '/' };
var route = new Route('');
route.all(function(req, res, next){
throw new Error('boom!');
});
route.dispatch(req, {}, function(err){
assert.ok(err)
assert.strictEqual(err.message, 'boom!')
done();
});
});
it('should handle single error handler', function(done) {
var req = { method: 'GET', url: '/' };
var route = new Route('');
route.all(function(err, req, res, next){
// this should not execute
throw new Error('should not be called')
});
route.dispatch(req, {}, done);
});
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.routes.error.js | test/app.routes.error.js | 'use strict'
var assert = require('node:assert')
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.VERB()', function(){
it('should not get invoked without error handler on error', function(done) {
var app = express();
app.use(function(req, res, next){
next(new Error('boom!'))
});
app.get('/bar', function(req, res){
res.send('hello, world!');
});
request(app)
.post('/bar')
.expect(500, /Error: boom!/, done);
});
it('should only call an error handling routing callback when an error is propagated', function(done){
var app = express();
var a = false;
var b = false;
var c = false;
var d = false;
app.get('/', function(req, res, next){
next(new Error('fabricated error'));
}, function(req, res, next) {
a = true;
next();
}, function(err, req, res, next){
b = true;
assert.strictEqual(err.message, 'fabricated error')
next(err);
}, function(err, req, res, next){
c = true;
assert.strictEqual(err.message, 'fabricated error')
next();
}, function(err, req, res, next){
d = true;
next();
}, function(req, res){
assert.ok(!a)
assert.ok(b)
assert.ok(c)
assert.ok(!d)
res.sendStatus(204);
});
request(app)
.get('/')
.expect(204, done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.vary.js | test/res.vary.js | 'use strict'
var express = require('..');
var request = require('supertest');
var utils = require('./support/utils');
describe('res.vary()', function(){
describe('with no arguments', function(){
it('should throw error', function (done) {
var app = express();
app.use(function (req, res) {
res.vary();
res.end();
});
request(app)
.get('/')
.expect(500, /field.*required/, done)
})
})
describe('with an empty array', function(){
it('should not set Vary', function (done) {
var app = express();
app.use(function (req, res) {
res.vary([]);
res.end();
});
request(app)
.get('/')
.expect(utils.shouldNotHaveHeader('Vary'))
.expect(200, done);
})
})
describe('with an array', function(){
it('should set the values', function (done) {
var app = express();
app.use(function (req, res) {
res.vary(['Accept', 'Accept-Language', 'Accept-Encoding']);
res.end();
});
request(app)
.get('/')
.expect('Vary', 'Accept, Accept-Language, Accept-Encoding')
.expect(200, done);
})
})
describe('with a string', function(){
it('should set the value', function (done) {
var app = express();
app.use(function (req, res) {
res.vary('Accept');
res.end();
});
request(app)
.get('/')
.expect('Vary', 'Accept')
.expect(200, done);
})
})
describe('when the value is present', function(){
it('should not add it again', function (done) {
var app = express();
app.use(function (req, res) {
res.vary('Accept');
res.vary('Accept-Encoding');
res.vary('Accept-Encoding');
res.vary('Accept-Encoding');
res.vary('Accept');
res.end();
});
request(app)
.get('/')
.expect('Vary', 'Accept, Accept-Encoding')
.expect(200, done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.ips.js | test/req.ips.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.ips', function(){
describe('when X-Forwarded-For is present', function(){
describe('when "trust proxy" is enabled', function(){
it('should return an array of the specified addresses', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res, next){
res.send(req.ips);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('["client","p1","p2"]', done);
})
it('should stop at first untrusted', function(done){
var app = express();
app.set('trust proxy', 2);
app.use(function(req, res, next){
res.send(req.ips);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('["p1","p2"]', done);
})
})
describe('when "trust proxy" is disabled', function(){
it('should return an empty array', function(done){
var app = express();
app.use(function(req, res, next){
res.send(req.ips);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('[]', done);
})
})
})
describe('when X-Forwarded-For is not present', function(){
it('should return []', function(done){
var app = express();
app.use(function(req, res, next){
res.send(req.ips);
});
request(app)
.get('/')
.expect('[]', done);
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.get.js | test/res.get.js | 'use strict'
var express = require('..');
var request = require('supertest');
describe('res', function(){
describe('.get(field)', function(){
it('should get the response header field', function (done) {
var app = express();
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/x-foo');
res.send(res.get('Content-Type'));
});
request(app)
.get('/')
.expect(200, 'text/x-foo', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.route.js | test/req.route.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.route', function(){
it('should be the executed Route', function(done){
var app = express();
app.get('/user/:id{/:op}', function(req, res, next){
res.header('path-1', req.route.path)
next();
});
app.get('/user/:id/edit', function(req, res){
res.header('path-2', req.route.path)
res.end();
});
request(app)
.get('/user/12/edit')
.expect('path-1', '/user/:id{/:op}')
.expect('path-2', '/user/:id/edit')
.expect(200, done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.param.js | test/app.param.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.param(names, fn)', function(){
it('should map the array', function(done){
var app = express();
app.param(['id', 'uid'], function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/post/:id', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
app.get('/user/:uid', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect(200, 'number:123', function (err) {
if (err) return done(err)
request(app)
.get('/post/123')
.expect('number:123', done)
})
})
})
describe('.param(name, fn)', function(){
it('should map logic for a single param', function(done){
var app = express();
app.param('id', function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect(200, 'number:123', done)
})
it('should only call once per request', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
req.user = user;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.user].join(' '));
});
request(app)
.get('/foo/bob')
.expect('2 1 bob', done);
})
it('should call when values differ', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
req.users = (req.users || []).concat(user);
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.users.join(',')].join(' '));
});
request(app)
.get('/foo/bob')
.expect('2 2 foo,bob', done);
})
it('should support altering req.params across routes', function(done) {
var app = express();
app.param('user', function(req, res, next, user) {
req.params.user = 'loki';
next();
});
app.get('/:user', function(req, res, next) {
next('route');
});
app.get('/:user', function (req, res) {
res.send(req.params.user);
});
request(app)
.get('/bob')
.expect('loki', done);
})
it('should not invoke without route handler', function(done) {
var app = express();
app.param('thing', function(req, res, next, thing) {
req.thing = thing;
next();
});
app.param('user', function(req, res, next, user) {
next(new Error('invalid invocation'))
});
app.post('/:user', function (req, res) {
res.send(req.params.user);
});
app.get('/:thing', function (req, res) {
res.send(req.thing);
});
request(app)
.get('/bob')
.expect(200, 'bob', done);
})
it('should work with encoded values', function(done){
var app = express();
app.param('name', function(req, res, next, name){
req.params.name = name;
next();
});
app.get('/user/:name', function(req, res){
var name = req.params.name;
res.send('' + name);
});
request(app)
.get('/user/foo%25bar')
.expect('foo%bar', done);
})
it('should catch thrown error', function(done){
var app = express();
app.param('id', function(req, res, next, id){
throw new Error('err!');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
request(app)
.get('/user/123')
.expect(500, done);
})
it('should catch thrown secondary error', function(done){
var app = express();
app.param('id', function(req, res, next, val){
process.nextTick(next);
});
app.param('id', function(req, res, next, id){
throw new Error('err!');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
request(app)
.get('/user/123')
.expect(500, done);
})
it('should defer to next route', function(done){
var app = express();
app.param('id', function(req, res, next, id){
next('route');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
app.get('/:name/123', function(req, res){
res.send('name');
});
request(app)
.get('/user/123')
.expect('name', done);
})
it('should defer all the param routes', function(done){
var app = express();
app.param('id', function(req, res, next, val){
if (val === 'new') return next('route');
return next();
});
app.all('/user/:id', function(req, res){
res.send('all.id');
});
app.get('/user/:id', function(req, res){
res.send('get.id');
});
app.get('/user/new', function(req, res){
res.send('get.new');
});
request(app)
.get('/user/new')
.expect('get.new', done);
})
it('should not call when values differ on error', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
if (user === 'foo') throw new Error('err!');
req.user = user;
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(err, req, res, next) {
res.status(500);
res.send([count, called, err.message].join(' '));
});
request(app)
.get('/foo/bob')
.expect(500, '0 1 err!', done)
});
it('should call when values differ when using "next"', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
if (user === 'foo') return next('route');
req.user = user;
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.user].join(' '));
});
request(app)
.get('/foo/bob')
.expect('1 2 bob', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/express.raw.js | test/express.raw.js | 'use strict'
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
var express = require('..')
var request = require('supertest')
const { Buffer } = require('node:buffer');
describe('express.raw()', function () {
before(function () {
this.app = createApp()
})
it('should parse application/octet-stream', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is tobi')
.expect(200, { buf: '746865207573657220697320746f6269' }, done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.raw())
app.post('/', function (req, res) {
if (Buffer.isBuffer(req.body)) {
res.json({ buf: req.body.toString('hex') })
} else {
res.json(req.body)
}
})
request(app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('stuff')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.set('Content-Length', '0')
.expect(200, { buf: '' }, done)
})
it('should handle empty message-body', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, { buf: '' }, done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.raw())
app.use(express.raw())
app.post('/', function (req, res) {
if (Buffer.isBuffer(req.body)) {
res.json({ buf: req.body.toString('hex') })
} else {
res.json(req.body)
}
})
request(app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is tobi')
.expect(200, { buf: '746865207573657220697320746f6269' }, done)
})
describe('with limit option', function () {
it('should 413 when over limit with Content-Length', function (done) {
var buf = Buffer.alloc(1028, '.')
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.set('Content-Length', '1028')
test.write(buf)
test.expect(413, done)
})
it('should 413 when over limit with chunked encoding', function (done) {
var buf = Buffer.alloc(1028, '.')
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.set('Transfer-Encoding', 'chunked')
test.write(buf)
test.expect(413, done)
})
it('should 413 when inflated body over limit', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex'))
test.expect(413, done)
})
it('should accept number of bytes', function (done) {
var buf = Buffer.alloc(1028, '.')
var app = createApp({ limit: 1024 })
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(buf)
test.expect(413, done)
})
it('should not change when options altered', function (done) {
var buf = Buffer.alloc(1028, '.')
var options = { limit: '1kb' }
var app = createApp(options)
options.limit = '100kb'
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(buf)
test.expect(413, done)
})
it('should not hang response', function (done) {
var buf = Buffer.alloc(10240, '.')
var app = createApp({ limit: '8kb' })
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(buf)
test.write(buf)
test.write(buf)
test.expect(413, done)
})
it('should not error when inflating', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a147040400', 'hex'))
test.expect(413, done)
})
})
describe('with inflate option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ inflate: false })
})
it('should not accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(415, '[encoding.unsupported] content encoding unsupported', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ inflate: true })
})
it('should accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
})
})
describe('with type option', function () {
describe('when "application/vnd+octets"', function () {
before(function () {
this.app = createApp({ type: 'application/vnd+octets' })
})
it('should parse for custom type', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/vnd+octets')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, { buf: '000102' }, done)
})
it('should ignore standard type', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, '', done)
})
})
describe('when ["application/octet-stream", "application/vnd+octets"]', function () {
before(function () {
this.app = createApp({
type: ['application/octet-stream', 'application/vnd+octets']
})
})
it('should parse "application/octet-stream"', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, { buf: '000102' }, done)
})
it('should parse "application/vnd+octets"', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/vnd+octets')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, { buf: '000102' }, done)
})
it('should ignore "application/x-foo"', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-foo')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, '', done)
})
})
describe('when a function', function () {
it('should parse when truthy value returned', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return req.headers['content-type'] === 'application/vnd.octet'
}
var test = request(app).post('/')
test.set('Content-Type', 'application/vnd.octet')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, { buf: '000102' }, done)
})
it('should work without content-type', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return true
}
var test = request(app).post('/')
test.write(Buffer.from('000102', 'hex'))
test.expect(200, { buf: '000102' }, done)
})
it('should not invoke without a body', function (done) {
var app = createApp({ type: accept })
function accept (req) {
throw new Error('oops!')
}
request(app)
.get('/')
.expect(404, done)
})
})
})
describe('with verify option', function () {
it('should assert value is function', function () {
assert.throws(createApp.bind(null, { verify: 'lol' }),
/TypeError: option verify must be function/)
})
it('should error from verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x00) throw new Error('no leading null')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('000102', 'hex'))
test.expect(403, '[entity.verify.failed] no leading null', done)
})
it('should allow custom codes', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x00) return
var err = new Error('no leading null')
err.status = 400
throw err
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('000102', 'hex'))
test.expect(400, '[entity.verify.failed] no leading null', done)
})
it('should allow pass-through', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x00) throw new Error('no leading null')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('0102', 'hex'))
test.expect(200, { buf: '0102' }, done)
})
})
describe('async local storage', function () {
before(function () {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(express.raw())
app.use(function (req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
next()
})
app.use(function (err, req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.status(err.status || 500)
res.send('[' + err.type + '] ' + err.message)
})
app.post('/', function (req, res) {
if (Buffer.isBuffer(req.body)) {
res.json({ buf: req.body.toString('hex') })
} else {
res.json(req.body)
}
})
this.app = app
})
it('should persist store', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is tobi')
.expect(200)
.expect('x-store-foo', 'bar')
.expect({ buf: '746865207573657220697320746f6269' })
.end(done)
})
it('should persist store when unmatched content-type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/fizzbuzz')
.send('buzz')
.expect(200)
.expect('x-store-foo', 'bar')
.end(done)
})
it('should persist store when inflated', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200)
test.expect('x-store-foo', 'bar')
test.expect({ buf: '6e616d653de8aeba' })
test.end(done)
})
it('should persist store when inflate error', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex'))
test.expect(400)
test.expect('x-store-foo', 'bar')
test.end(done)
})
it('should persist store when limit exceeded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is ' + Buffer.alloc(1024 * 100, '.').toString())
.expect(413)
.expect('x-store-foo', 'bar')
.end(done)
})
})
describe('charset', function () {
before(function () {
this.app = createApp()
})
it('should ignore charset', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/octet-stream; charset=utf-8')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, { buf: '6e616d6520697320e8aeba' }, done)
})
})
describe('encoding', function () {
before(function () {
this.app = createApp({ limit: '10kb' })
})
it('should parse without encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
it('should support identity encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'identity')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
it('should support gzip encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
it('should support deflate encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'deflate')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
it('should be case-insensitive', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'GZIP')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, { buf: '6e616d653de8aeba' }, done)
})
it('should 415 on unknown encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'nulls')
test.set('Content-Type', 'application/octet-stream')
test.write(Buffer.from('000000000000', 'hex'))
test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)
})
})
})
function createApp (options) {
var app = express()
app.use(express.raw(options))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send(String(req.headers['x-error-property']
? err[req.headers['x-error-property']]
: ('[' + err.type + '] ' + err.message)))
})
app.post('/', function (req, res) {
if (Buffer.isBuffer(req.body)) {
res.json({ buf: req.body.toString('hex') })
} else {
res.json(req.body)
}
})
return app
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.clearCookie.js | test/res.clearCookie.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('res', function(){
describe('.clearCookie(name)', function(){
it('should set a cookie passed expiry', function(done){
var app = express();
app.use(function(req, res){
res.clearCookie('sid').end();
});
request(app)
.get('/')
.expect('Set-Cookie', 'sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
.expect(200, done)
})
})
describe('.clearCookie(name, options)', function(){
it('should set the given params', function(done){
var app = express();
app.use(function(req, res){
res.clearCookie('sid', { path: '/admin' }).end();
});
request(app)
.get('/')
.expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
.expect(200, done)
})
it('should ignore maxAge', function(done){
var app = express();
app.use(function(req, res){
res.clearCookie('sid', { path: '/admin', maxAge: 1000 }).end();
});
request(app)
.get('/')
.expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
.expect(200, done)
})
it('should ignore user supplied expires param', function(done){
var app = express();
app.use(function(req, res){
res.clearCookie('sid', { path: '/admin', expires: new Date() }).end();
});
request(app)
.get('/')
.expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
.expect(200, done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.route.js | test/app.route.js | 'use strict'
var express = require('../');
var request = require('supertest');
describe('app.route', function(){
it('should return a new route', function(done){
var app = express();
app.route('/foo')
.get(function(req, res) {
res.send('get');
})
.post(function(req, res) {
res.send('post');
});
request(app)
.post('/foo')
.expect('post', done);
});
it('should all .VERB after .all', function(done){
var app = express();
app.route('/foo')
.all(function(req, res, next) {
next();
})
.get(function(req, res) {
res.send('get');
})
.post(function(req, res) {
res.send('post');
});
request(app)
.post('/foo')
.expect('post', done);
});
it('should support dynamic routes', function(done){
var app = express();
app.route('/:foo')
.get(function(req, res) {
res.send(req.params.foo);
});
request(app)
.get('/test')
.expect('test', done);
});
it('should not error on empty routes', function(done){
var app = express();
app.route('/:foo');
request(app)
.get('/test')
.expect(404, done);
});
describe('promise support', function () {
it('should pass rejected promise value', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
return Promise.reject(new Error('boom!'))
})
route.all(function helloWorld (req, res) {
res.send('hello, world!')
})
route.all(function handleError (err, req, res, next) {
res.status(500)
res.send('caught: ' + err.message)
})
request(app)
.get('/foo')
.expect(500, 'caught: boom!', done)
})
it('should pass rejected promise without value', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
return Promise.reject()
})
route.all(function helloWorld (req, res) {
res.send('hello, world!')
})
route.all(function handleError (err, req, res, next) {
res.status(500)
res.send('caught: ' + err.message)
})
request(app)
.get('/foo')
.expect(500, 'caught: Rejected promise', done)
})
it('should ignore resolved promise', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
res.send('saw GET /foo')
return Promise.resolve('foo')
})
route.all(function () {
done(new Error('Unexpected route invoke'))
})
request(app)
.get('/foo')
.expect(200, 'saw GET /foo', done)
})
describe('error handling', function () {
it('should pass rejected promise value', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
return Promise.reject(new Error('boom!'))
})
route.all(function handleError (err, req, res, next) {
return Promise.reject(new Error('caught: ' + err.message))
})
route.all(function handleError (err, req, res, next) {
res.status(500)
res.send('caught again: ' + err.message)
})
request(app)
.get('/foo')
.expect(500, 'caught again: caught: boom!', done)
})
it('should pass rejected promise without value', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
return Promise.reject(new Error('boom!'))
})
route.all(function handleError (err, req, res, next) {
return Promise.reject()
})
route.all(function handleError (err, req, res, next) {
res.status(500)
res.send('caught again: ' + err.message)
})
request(app)
.get('/foo')
.expect(500, 'caught again: Rejected promise', done)
})
it('should ignore resolved promise', function (done) {
var app = express()
var route = app.route('/foo')
route.all(function createError (req, res, next) {
return Promise.reject(new Error('boom!'))
})
route.all(function handleError (err, req, res, next) {
res.status(500)
res.send('caught: ' + err.message)
return Promise.resolve('foo')
})
route.all(function () {
done(new Error('Unexpected route invoke'))
})
request(app)
.get('/foo')
.expect(500, 'caught: boom!', done)
})
})
})
});
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.locals.js | test/res.locals.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('res', function(){
describe('.locals', function(){
it('should be empty by default', function(done){
var app = express();
app.use(function(req, res){
res.json(res.locals)
});
request(app)
.get('/')
.expect(200, {}, done)
})
})
it('should work when mounted', function(done){
var app = express();
var blog = express();
app.use(blog);
blog.use(function(req, res, next){
res.locals.foo = 'bar';
next();
});
app.use(function(req, res){
res.json(res.locals)
});
request(app)
.get('/')
.expect(200, { foo: 'bar' }, done)
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.sendStatus.js | test/res.sendStatus.js | 'use strict'
var express = require('..')
var request = require('supertest')
describe('res', function () {
describe('.sendStatus(statusCode)', function () {
it('should send the status code and message as body', function (done) {
var app = express();
app.use(function(req, res){
res.sendStatus(201);
});
request(app)
.get('/')
.expect(201, 'Created', done);
})
it('should work with unknown code', function (done) {
var app = express();
app.use(function(req, res){
res.sendStatus(599);
});
request(app)
.get('/')
.expect(599, '599', done);
})
it('should raise error for invalid status code', function (done) {
var app = express()
app.use(function (req, res) {
res.sendStatus(undefined).end()
})
request(app)
.get('/')
.expect(500, /TypeError: Invalid status code/, done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.protocol.js | test/req.protocol.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.protocol', function(){
it('should return the protocol string', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.expect('http', done);
})
describe('when "trust proxy" is enabled', function(){
it('should respect X-Forwarded-Proto', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('https', done);
})
it('should default to the socket addr if X-Forwarded-Proto not present', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
req.socket.encrypted = true;
res.end(req.protocol);
});
request(app)
.get('/')
.expect('https', done);
})
it('should ignore X-Forwarded-Proto if socket addr not trusted', function(done){
var app = express();
app.set('trust proxy', '10.0.0.1');
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('http', done);
})
it('should default to http', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.expect('http', done);
})
describe('when trusting hop count', function () {
it('should respect X-Forwarded-Proto', function (done) {
var app = express();
app.set('trust proxy', 1);
app.use(function (req, res) {
res.end(req.protocol);
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('https', done);
})
})
})
describe('when "trust proxy" is disabled', function(){
it('should ignore X-Forwarded-Proto', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('http', done);
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.host.js | test/req.host.js | 'use strict'
var express = require('../')
, request = require('supertest')
describe('req', function(){
describe('.host', function(){
it('should return the Host when present', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.post('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
it('should strip port number', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.post('/')
.set('Host', 'example.com:3000')
.expect(200, 'example.com:3000', done);
})
it('should return undefined otherwise', function(done){
var app = express();
app.use(function(req, res){
req.headers.host = null;
res.end(String(req.host));
});
request(app)
.post('/')
.expect('undefined', done);
})
it('should work with IPv6 Host', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.post('/')
.set('Host', '[::1]')
.expect('[::1]', done);
})
it('should work with IPv6 Host and port', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.post('/')
.set('Host', '[::1]:3000')
.expect(200, '[::1]:3000', done);
})
describe('when "trust proxy" is enabled', function(){
it('should respect X-Forwarded-Host', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.host);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com')
.expect('example.com', done);
})
it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){
var app = express();
app.set('trust proxy', '10.0.0.1');
app.use(function(req, res){
res.end(req.host);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com')
.expect('localhost', done);
})
it('should default to Host', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.host);
});
request(app)
.get('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
describe('when trusting hop count', function () {
it('should respect X-Forwarded-Host', function (done) {
var app = express();
app.set('trust proxy', 1);
app.use(function (req, res) {
res.end(req.host);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com')
.expect('example.com', done);
})
})
})
describe('when "trust proxy" is disabled', function(){
it('should ignore X-Forwarded-Host', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'evil')
.expect('localhost', done);
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.attachment.js | test/res.attachment.js | 'use strict'
const { Buffer } = require('node:buffer');
var express = require('../')
, request = require('supertest');
describe('res', function(){
describe('.attachment()', function(){
it('should Content-Disposition to attachment', function(done){
var app = express();
app.use(function(req, res){
res.attachment().send('foo');
});
request(app)
.get('/')
.expect('Content-Disposition', 'attachment', done);
})
})
describe('.attachment(filename)', function(){
it('should add the filename param', function(done){
var app = express();
app.use(function(req, res){
res.attachment('/path/to/image.png');
res.send('foo');
});
request(app)
.get('/')
.expect('Content-Disposition', 'attachment; filename="image.png"', done);
})
it('should set the Content-Type', function(done){
var app = express();
app.use(function(req, res){
res.attachment('/path/to/image.png');
res.send(Buffer.alloc(4, '.'))
});
request(app)
.get('/')
.expect('Content-Type', 'image/png', done);
})
})
describe('.attachment(utf8filename)', function(){
it('should add the filename and filename* params', function(done){
var app = express();
app.use(function(req, res){
res.attachment('/locales/日本語.txt');
res.send('japanese');
});
request(app)
.get('/')
.expect('Content-Disposition', 'attachment; filename="???.txt"; filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt')
.expect(200, done);
})
it('should set the Content-Type', function(done){
var app = express();
app.use(function(req, res){
res.attachment('/locales/日本語.txt');
res.send('japanese');
});
request(app)
.get('/')
.expect('Content-Type', 'text/plain; charset=utf-8', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/Router.js | test/Router.js | 'use strict'
var after = require('after');
var express = require('../')
, Router = express.Router
, methods = require('../lib/utils').methods
, assert = require('node:assert');
describe('Router', function () {
it('should return a function with router methods', function () {
var router = new Router();
assert(typeof router === 'function')
assert(typeof router.get === 'function')
assert(typeof router.handle === 'function')
assert(typeof router.use === 'function')
});
it('should support .use of other routers', function (done) {
var router = new Router();
var another = new Router();
another.get('/bar', function (req, res) {
res.end();
});
router.use('/foo', another);
router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, function () { });
});
it('should support dynamic routes', function (done) {
var router = new Router();
var another = new Router();
another.get('/:bar', function (req, res) {
assert.strictEqual(req.params.bar, 'route')
res.end();
});
router.use('/:foo', another);
router.handle({ url: '/test/route', method: 'GET' }, { end: done }, function () { });
});
it('should handle blank URL', function (done) {
var router = new Router();
router.use(function (req, res) {
throw new Error('should not be called')
});
router.handle({ url: '', method: 'GET' }, {}, done);
});
it('should handle missing URL', function (done) {
var router = new Router()
router.use(function (req, res) {
throw new Error('should not be called')
})
router.handle({ method: 'GET' }, {}, done)
})
it('handle missing method', function (done) {
var all = false
var router = new Router()
var route = router.route('/foo')
var use = false
route.post(function (req, res, next) { next(new Error('should not run')) })
route.all(function (req, res, next) {
all = true
next()
})
route.get(function (req, res, next) { next(new Error('should not run')) })
router.get('/foo', function (req, res, next) { next(new Error('should not run')) })
router.use(function (req, res, next) {
use = true
next()
})
router.handle({ url: '/foo' }, {}, function (err) {
if (err) return done(err)
assert.ok(all)
assert.ok(use)
done()
})
})
it('should not stack overflow with many registered routes', function (done) {
this.timeout(5000) // long-running test
var handler = function (req, res) { res.end(new Error('wrong handler')) };
var router = new Router();
for (var i = 0; i < 6000; i++) {
router.get('/thing' + i, handler)
}
router.get('/', function (req, res) {
res.end();
});
router.handle({ url: '/', method: 'GET' }, { end: done }, function () { });
});
it('should not stack overflow with a large sync route stack', function (done) {
this.timeout(5000) // long-running test
var router = new Router()
router.get('/foo', function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
router.get('/foo', function (req, res, next) {
req.counter++
next()
})
}
router.get('/foo', function (req, res) {
assert.strictEqual(req.counter, 6000)
res.end()
})
router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) {
assert(!err, err);
});
})
it('should not stack overflow with a large sync middleware stack', function (done) {
this.timeout(5000) // long-running test
var router = new Router()
router.use(function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
router.use(function (req, res, next) {
req.counter++
next()
})
}
router.use(function (req, res) {
assert.strictEqual(req.counter, 6000)
res.end()
})
router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) {
assert(!err, err);
})
})
describe('.handle', function () {
it('should dispatch', function (done) {
var router = new Router();
router.route('/foo').get(function (req, res) {
res.send('foo');
});
var res = {
send: function (val) {
assert.strictEqual(val, 'foo')
done();
}
}
router.handle({ url: '/foo', method: 'GET' }, res, function () { });
})
})
describe('.multiple callbacks', function () {
it('should throw if a callback is null', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all(null);
})
})
it('should throw if a callback is undefined', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all(undefined);
})
})
it('should throw if a callback is not a function', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all('not a function');
})
})
it('should not throw if all callbacks are functions', function () {
var router = new Router();
router.route('/foo').all(function () { }).all(function () { });
})
})
describe('error', function () {
it('should skip non error middleware', function (done) {
var router = new Router();
router.get('/foo', function (req, res, next) {
next(new Error('foo'));
});
router.get('/bar', function (req, res, next) {
next(new Error('bar'));
});
router.use(function (req, res, next) {
assert(false);
});
router.use(function (err, req, res, next) {
assert.equal(err.message, 'foo');
done();
});
router.handle({ url: '/foo', method: 'GET' }, {}, done);
});
it('should handle throwing inside routes with params', function (done) {
var router = new Router();
router.get('/foo/:id', function () {
throw new Error('foo');
});
router.use(function (req, res, next) {
assert(false);
});
router.use(function (err, req, res, next) {
assert.equal(err.message, 'foo');
done();
});
router.handle({ url: '/foo/2', method: 'GET' }, {}, function () { });
});
it('should handle throwing in handler after async param', function (done) {
var router = new Router();
router.param('user', function (req, res, next, val) {
process.nextTick(function () {
req.user = val;
next();
});
});
router.use('/:user', function (req, res, next) {
throw new Error('oh no!');
});
router.use(function (err, req, res, next) {
assert.equal(err.message, 'oh no!');
done();
});
router.handle({ url: '/bob', method: 'GET' }, {}, function () { });
});
it('should handle throwing inside error handlers', function (done) {
var router = new Router();
router.use(function (req, res, next) {
throw new Error('boom!');
});
router.use(function (err, req, res, next) {
throw new Error('oops');
});
router.use(function (err, req, res, next) {
assert.equal(err.message, 'oops');
done();
});
router.handle({ url: '/', method: 'GET' }, {}, done);
});
})
describe('FQDN', function () {
it('should not obscure FQDNs', function (done) {
var request = { hit: 0, url: 'http://example.com/foo', method: 'GET' };
var router = new Router();
router.use(function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, 'http://example.com/foo');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 1);
done();
});
});
it('should ignore FQDN in search', function (done) {
var request = { hit: 0, url: '/proxy?url=http://example.com/blog/post/1', method: 'GET' };
var router = new Router();
router.use('/proxy', function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, '/?url=http://example.com/blog/post/1');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 1);
done();
});
});
it('should ignore FQDN in path', function (done) {
var request = { hit: 0, url: '/proxy/http://example.com/blog/post/1', method: 'GET' };
var router = new Router();
router.use('/proxy', function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, '/http://example.com/blog/post/1');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 1);
done();
});
});
it('should adjust FQDN req.url', function (done) {
var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' };
var router = new Router();
router.use('/blog', function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, 'http://example.com/post/1');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 1);
done();
});
});
it('should adjust FQDN req.url with multiple handlers', function (done) {
var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' };
var router = new Router();
router.use(function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, 'http://example.com/blog/post/1');
next();
});
router.use('/blog', function (req, res, next) {
assert.equal(req.hit++, 1);
assert.equal(req.url, 'http://example.com/post/1');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 2);
done();
});
});
it('should adjust FQDN req.url with multiple routed handlers', function (done) {
var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' };
var router = new Router();
router.use('/blog', function (req, res, next) {
assert.equal(req.hit++, 0);
assert.equal(req.url, 'http://example.com/post/1');
next();
});
router.use('/blog', function (req, res, next) {
assert.equal(req.hit++, 1);
assert.equal(req.url, 'http://example.com/post/1');
next();
});
router.use(function (req, res, next) {
assert.equal(req.hit++, 2);
assert.equal(req.url, 'http://example.com/blog/post/1');
next();
});
router.handle(request, {}, function (err) {
if (err) return done(err);
assert.equal(request.hit, 3);
done();
});
});
})
describe('.all', function () {
it('should support using .all to capture all http verbs', function (done) {
var router = new Router();
var count = 0;
router.all('/foo', function () { count++; });
var url = '/foo?bar=baz';
methods.forEach(function testMethod(method) {
router.handle({ url: url, method: method }, {}, function () { });
});
assert.equal(count, methods.length);
done();
})
})
describe('.use', function () {
it('should require middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/') }, /argument handler is required/)
})
it('should reject string as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', 'foo') }, /argument handler must be a function/)
})
it('should reject number as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', 42) }, /argument handler must be a function/)
})
it('should reject null as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', null) }, /argument handler must be a function/)
})
it('should reject Date as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', new Date()) }, /argument handler must be a function/)
})
it('should be called for any URL', function (done) {
var cb = after(4, done)
var router = new Router()
function no() {
throw new Error('should not be called')
}
router.use(function (req, res) {
res.end()
})
router.handle({ url: '/', method: 'GET' }, { end: cb }, no)
router.handle({ url: '/foo', method: 'GET' }, { end: cb }, no)
router.handle({ url: 'foo', method: 'GET' }, { end: cb }, no)
router.handle({ url: '*', method: 'GET' }, { end: cb }, no)
})
it('should accept array of middleware', function (done) {
var count = 0;
var router = new Router();
function fn1(req, res, next) {
assert.equal(++count, 1);
next();
}
function fn2(req, res, next) {
assert.equal(++count, 2);
next();
}
router.use([fn1, fn2], function (req, res) {
assert.equal(++count, 3);
done();
});
router.handle({ url: '/foo', method: 'GET' }, {}, function () { });
})
})
describe('.param', function () {
it('should require function', function () {
var router = new Router();
assert.throws(router.param.bind(router, 'id'), /argument fn is required/);
});
it('should reject non-function', function () {
var router = new Router();
assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/);
});
it('should call param function when routing VERBS', function (done) {
var router = new Router();
router.param('id', function (req, res, next, id) {
assert.equal(id, '123');
next();
});
router.get('/foo/:id/bar', function (req, res, next) {
assert.equal(req.params.id, '123');
next();
});
router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done);
});
it('should call param function when routing middleware', function (done) {
var router = new Router();
router.param('id', function (req, res, next, id) {
assert.equal(id, '123');
next();
});
router.use('/foo/:id/bar', function (req, res, next) {
assert.equal(req.params.id, '123');
assert.equal(req.url, '/baz');
next();
});
router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done);
});
it('should only call once per request', function (done) {
var count = 0;
var req = { url: '/foo/bob/bar', method: 'get' };
var router = new Router();
var sub = new Router();
sub.get('/bar', function (req, res, next) {
next();
});
router.param('user', function (req, res, next, user) {
count++;
req.user = user;
next();
});
router.use('/foo/:user/', new Router());
router.use('/foo/:user/', sub);
router.handle(req, {}, function (err) {
if (err) return done(err);
assert.equal(count, 1);
assert.equal(req.user, 'bob');
done();
});
});
it('should call when values differ', function (done) {
var count = 0;
var req = { url: '/foo/bob/bar', method: 'get' };
var router = new Router();
var sub = new Router();
sub.get('/bar', function (req, res, next) {
next();
});
router.param('user', function (req, res, next, user) {
count++;
req.user = user;
next();
});
router.use('/foo/:user/', new Router());
router.use('/:user/bob/', sub);
router.handle(req, {}, function (err) {
if (err) return done(err);
assert.equal(count, 2);
assert.equal(req.user, 'foo');
done();
});
});
});
describe('parallel requests', function () {
it('should not mix requests', function (done) {
var req1 = { url: '/foo/50/bar', method: 'get' };
var req2 = { url: '/foo/10/bar', method: 'get' };
var router = new Router();
var sub = new Router();
var cb = after(2, done)
sub.get('/bar', function (req, res, next) {
next();
});
router.param('ms', function (req, res, next, ms) {
ms = parseInt(ms, 10);
req.ms = ms;
setTimeout(next, ms);
});
router.use('/foo/:ms/', new Router());
router.use('/foo/:ms/', sub);
router.handle(req1, {}, function (err) {
assert.ifError(err);
assert.equal(req1.ms, 50);
assert.equal(req1.originalUrl, '/foo/50/bar');
cb()
});
router.handle(req2, {}, function (err) {
assert.ifError(err);
assert.equal(req2.ms, 10);
assert.equal(req2.originalUrl, '/foo/10/bar');
cb()
});
});
});
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.render.js | test/app.render.js | 'use strict'
var assert = require('node:assert')
var express = require('..');
var path = require('node:path')
var tmpl = require('./support/tmpl');
describe('app', function(){
describe('.render(name, fn)', function(){
it('should support absolute paths', function(done){
var app = createApp();
app.locals.user = { name: 'tobi' };
app.render(path.join(__dirname, 'fixtures', 'user.tmpl'), function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should support absolute paths with "view engine"', function(done){
var app = createApp();
app.set('view engine', 'tmpl');
app.locals.user = { name: 'tobi' };
app.render(path.join(__dirname, 'fixtures', 'user'), function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should expose app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should support index.<engine>', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.set('view engine', 'tmpl');
app.render('blog/post', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<h1>blog post</h1>')
done();
})
})
it('should handle render error throws', function(done){
var app = express();
function View(name, options){
this.name = name;
this.path = 'fale';
}
View.prototype.render = function(options, fn){
throw new Error('err!');
};
app.set('view', View);
app.render('something', function(err, str){
assert.ok(err)
assert.strictEqual(err.message, 'err!')
done();
})
})
describe('when the file does not exist', function(){
it('should provide a helpful error', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.render('rawr.tmpl', function (err) {
assert.ok(err)
assert.equal(err.message, 'Failed to lookup view "rawr.tmpl" in views directory "' + path.join(__dirname, 'fixtures') + '"')
done();
});
})
})
describe('when an error occurs', function(){
it('should invoke the callback', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.render('user.tmpl', function (err) {
assert.ok(err)
assert.equal(err.name, 'RenderError')
done()
})
})
})
describe('when an extension is given', function(){
it('should render the template', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.render('email.tmpl', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>This is an email</p>')
done();
})
})
})
describe('when "view engine" is given', function(){
it('should render the template', function(done){
var app = createApp();
app.set('view engine', 'tmpl');
app.set('views', path.join(__dirname, 'fixtures'))
app.render('email', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>This is an email</p>')
done();
})
})
})
describe('when "views" is given', function(){
it('should lookup the file in the path', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures', 'default_layout'))
app.locals.user = { name: 'tobi' };
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
describe('when array of paths', function(){
it('should lookup the file in the path', function(done){
var app = createApp();
var views = [
path.join(__dirname, 'fixtures', 'local_layout'),
path.join(__dirname, 'fixtures', 'default_layout')
]
app.set('views', views);
app.locals.user = { name: 'tobi' };
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<span>tobi</span>')
done();
})
})
it('should lookup in later paths until found', function(done){
var app = createApp();
var views = [
path.join(__dirname, 'fixtures', 'local_layout'),
path.join(__dirname, 'fixtures', 'default_layout')
]
app.set('views', views);
app.locals.name = 'tobi';
app.render('name.tmpl', function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should error if file does not exist', function(done){
var app = createApp();
var views = [
path.join(__dirname, 'fixtures', 'local_layout'),
path.join(__dirname, 'fixtures', 'default_layout')
]
app.set('views', views);
app.locals.name = 'tobi';
app.render('pet.tmpl', function (err, str) {
assert.ok(err)
assert.equal(err.message, 'Failed to lookup view "pet.tmpl" in views directories "' + views[0] + '" or "' + views[1] + '"')
done();
})
})
})
})
describe('when a "view" constructor is given', function(){
it('should create an instance of it', function(done){
var app = express();
function View(name, options){
this.name = name;
this.path = 'path is required by application.js as a signal of success even though it is not used there.';
}
View.prototype.render = function(options, fn){
fn(null, 'abstract engine');
};
app.set('view', View);
app.render('something', function(err, str){
if (err) return done(err);
assert.strictEqual(str, 'abstract engine')
done();
})
})
})
describe('caching', function(){
it('should always lookup view without cache', function(done){
var app = express();
var count = 0;
function View(name, options){
this.name = name;
this.path = 'fake';
count++;
}
View.prototype.render = function(options, fn){
fn(null, 'abstract engine');
};
app.set('view cache', false);
app.set('view', View);
app.render('something', function(err, str){
if (err) return done(err);
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', function(err, str){
if (err) return done(err);
assert.strictEqual(count, 2)
assert.strictEqual(str, 'abstract engine')
done();
})
})
})
it('should cache with "view cache" setting', function(done){
var app = express();
var count = 0;
function View(name, options){
this.name = name;
this.path = 'fake';
count++;
}
View.prototype.render = function(options, fn){
fn(null, 'abstract engine');
};
app.set('view cache', true);
app.set('view', View);
app.render('something', function(err, str){
if (err) return done(err);
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', function(err, str){
if (err) return done(err);
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
done();
})
})
})
})
})
describe('.render(name, options, fn)', function(){
it('should render the template', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
var user = { name: 'tobi' };
app.render('user.tmpl', { user: user }, function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should expose app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.render('user.tmpl', {}, function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should give precedence to app.render() locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
var jane = { name: 'jane' };
app.render('user.tmpl', { user: jane }, function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>jane</p>')
done();
})
})
describe('caching', function(){
it('should cache with cache option', function(done){
var app = express();
var count = 0;
function View(name, options){
this.name = name;
this.path = 'fake';
count++;
}
View.prototype.render = function(options, fn){
fn(null, 'abstract engine');
};
app.set('view cache', false);
app.set('view', View);
app.render('something', {cache: true}, function(err, str){
if (err) return done(err);
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', {cache: true}, function(err, str){
if (err) return done(err);
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
done();
})
})
})
})
})
})
function createApp() {
var app = express();
app.engine('.tmpl', tmpl);
return app;
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/express.urlencoded.js | test/express.urlencoded.js | 'use strict'
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
const { Buffer } = require('node:buffer');
var express = require('..')
var request = require('supertest')
describe('express.urlencoded()', function () {
before(function () {
this.app = createApp()
})
it('should parse x-www-form-urlencoded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.urlencoded())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Content-Length', '0')
.send('')
.expect(200, '{}', done)
})
it('should handle empty message-body', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, '{}', done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.urlencoded())
app.use(express.urlencoded())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should not parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user[name][first]":"Tobi"}', done)
})
describe('with extended option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ extended: false })
})
it('should not parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user[name][first]":"Tobi"}', done)
})
it('should parse multiple key instances', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=Tobi&user=Loki')
.expect(200, '{"user":["Tobi","Loki"]}', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ extended: true })
})
it('should parse multiple key instances', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=Tobi&user=Loki')
.expect(200, '{"user":["Tobi","Loki"]}', done)
})
it('should parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)
})
it('should parse parameters with dots', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user.name=Tobi')
.expect(200, '{"user.name":"Tobi"}', done)
})
it('should parse fully-encoded extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user%5Bname%5D%5Bfirst%5D=Tobi')
.expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)
})
it('should parse array index notation', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('foo[0]=bar&foo[1]=baz')
.expect(200, '{"foo":["bar","baz"]}', done)
})
it('should parse array index notation with large array', function (done) {
var str = 'f[0]=0'
for (var i = 1; i < 500; i++) {
str += '&f[' + i + ']=' + i.toString(16)
}
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(str)
.expect(function (res) {
var obj = JSON.parse(res.text)
assert.strictEqual(Object.keys(obj).length, 1)
assert.strictEqual(Array.isArray(obj.f), true)
assert.strictEqual(obj.f.length, 500)
})
.expect(200, done)
})
it('should parse array of objects syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!')
.expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done)
})
it('should parse deep object', function (done) {
var str = 'foo'
for (var i = 0; i < 32; i++) {
str += '[p]'
}
str += '=bar'
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(str)
.expect(function (res) {
var obj = JSON.parse(res.text)
assert.strictEqual(Object.keys(obj).length, 1)
assert.strictEqual(typeof obj.foo, 'object')
var depth = 0
var ref = obj.foo
while ((ref = ref.p)) { depth++ }
assert.strictEqual(depth, 32)
})
.expect(200, done)
})
})
})
describe('with inflate option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ inflate: false })
})
it('should not accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(415, '[encoding.unsupported] content encoding unsupported', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ inflate: true })
})
it('should accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
})
})
describe('with limit option', function () {
it('should 413 when over limit with Content-Length', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Content-Length', '1028')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should 413 when over limit with chunked encoding', function (done) {
var app = createApp({ limit: '1kb' })
var buf = Buffer.alloc(1024, '.')
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.set('Transfer-Encoding', 'chunked')
test.write('str=')
test.write(buf.toString())
test.expect(413, done)
})
it('should 413 when inflated body over limit', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', 'hex'))
test.expect(413, done)
})
it('should accept number of bytes', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: 1024 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should not change when options altered', function (done) {
var buf = Buffer.alloc(1024, '.')
var options = { limit: '1kb' }
var app = createApp(options)
options.limit = '100kb'
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should not hang response', function (done) {
var app = createApp({ limit: '8kb' })
var buf = Buffer.alloc(10240, '.')
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(buf)
test.write(buf)
test.write(buf)
test.expect(413, done)
})
it('should not error when inflating', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', 'hex'))
test.expect(413, done)
})
})
describe('with parameterLimit option', function () {
describe('with extended: false', function () {
it('should reject 0', function () {
assert.throws(createApp.bind(null, { extended: false, parameterLimit: 0 }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should reject string', function () {
assert.throws(createApp.bind(null, { extended: false, parameterLimit: 'beep' }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should 413 if over limit', function (done) {
request(createApp({ extended: false, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, '[parameters.too.many] too many parameters', done)
})
it('should work when at the limit', function (done) {
request(createApp({ extended: false, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10))
.expect(expectKeyCount(10))
.expect(200, done)
})
it('should work if number is floating point', function (done) {
request(createApp({ extended: false, parameterLimit: 10.1 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, /too many parameters/, done)
})
it('should work with large limit', function (done) {
request(createApp({ extended: false, parameterLimit: 5000 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(5000))
.expect(expectKeyCount(5000))
.expect(200, done)
})
it('should work with Infinity limit', function (done) {
request(createApp({ extended: false, parameterLimit: Infinity }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10000))
.expect(expectKeyCount(10000))
.expect(200, done)
})
})
describe('with extended: true', function () {
it('should reject 0', function () {
assert.throws(createApp.bind(null, { extended: true, parameterLimit: 0 }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should reject string', function () {
assert.throws(createApp.bind(null, { extended: true, parameterLimit: 'beep' }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should 413 if over limit', function (done) {
request(createApp({ extended: true, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, '[parameters.too.many] too many parameters', done)
})
it('should work when at the limit', function (done) {
request(createApp({ extended: true, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10))
.expect(expectKeyCount(10))
.expect(200, done)
})
it('should work if number is floating point', function (done) {
request(createApp({ extended: true, parameterLimit: 10.1 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, /too many parameters/, done)
})
it('should work with large limit', function (done) {
request(createApp({ extended: true, parameterLimit: 5000 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(5000))
.expect(expectKeyCount(5000))
.expect(200, done)
})
it('should work with Infinity limit', function (done) {
request(createApp({ extended: true, parameterLimit: Infinity }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10000))
.expect(expectKeyCount(10000))
.expect(200, done)
})
})
})
describe('with type option', function () {
describe('when "application/vnd.x-www-form-urlencoded"', function () {
before(function () {
this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' })
})
it('should parse for custom type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/vnd.x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore standard type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '', done)
})
})
describe('when ["urlencoded", "application/x-pairs"]', function () {
before(function () {
this.app = createApp({
type: ['urlencoded', 'application/x-pairs']
})
})
it('should parse "application/x-www-form-urlencoded"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should parse "application/x-pairs"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-pairs')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore application/x-foo', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-foo')
.send('user=tobi')
.expect(200, '', done)
})
})
describe('when a function', function () {
it('should parse when truthy value returned', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return req.headers['content-type'] === 'application/vnd.something'
}
request(app)
.post('/')
.set('Content-Type', 'application/vnd.something')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should work without content-type', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return true
}
var test = request(app).post('/')
test.write('user=tobi')
test.expect(200, '{"user":"tobi"}', done)
})
it('should not invoke without a body', function (done) {
var app = createApp({ type: accept })
function accept (req) {
throw new Error('oops!')
}
request(app)
.get('/')
.expect(404, done)
})
})
})
describe('with verify option', function () {
it('should assert value if function', function () {
assert.throws(createApp.bind(null, { verify: 'lol' }),
/TypeError: option verify must be function/)
})
it('should error from verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x20) throw new Error('no leading space')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(403, '[entity.verify.failed] no leading space', done)
})
it('should allow custom codes', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x20) return
var err = new Error('no leading space')
err.status = 400
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(400, '[entity.verify.failed] no leading space', done)
})
it('should allow custom type', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x20) return
var err = new Error('no leading space')
err.type = 'foo.bar'
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(403, '[foo.bar] no leading space', done)
})
it('should allow pass-through', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should 415 on unknown charset prior to verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
throw new Error('unexpected verify call')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus')
test.write(Buffer.from('00000000', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)
})
})
describe('async local storage', function () {
before(function () {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(express.urlencoded())
app.use(function (req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
next()
})
app.use(function (err, req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.status(err.status || 500)
res.send('[' + err.type + '] ' + err.message)
})
app.post('/', function (req, res) {
res.json(req.body)
})
this.app = app
})
it('should persist store', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('{"user":"tobi"}')
.end(done)
})
it('should persist store when unmatched content-type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/fizzbuzz')
.send('buzz')
.expect(200)
.expect('x-store-foo', 'bar')
.end(done)
})
it('should persist store when inflated', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200)
test.expect('x-store-foo', 'bar')
test.expect('{"name":"论"}')
test.end(done)
})
it('should persist store when inflate error', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex'))
test.expect(400)
test.expect('x-store-foo', 'bar')
test.end(done)
})
it('should persist store when limit exceeded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=' + Buffer.alloc(1024 * 100, '.').toString())
.expect(413)
.expect('x-store-foo', 'bar')
.end(done)
})
})
describe('charset', function () {
before(function () {
this.app = createApp()
})
it('should parse utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should parse when content-length != char length', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
test.set('Content-Length', '7')
test.write(Buffer.from('746573743dc3a5', 'hex'))
test.expect(200, '{"test":"å"}', done)
})
it('should default to utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should fail on unknown charset', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r')
test.write(Buffer.from('6e616d653dcec5d4', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done)
})
})
describe('encoding', function () {
before(function () {
this.app = createApp({ limit: '10kb' })
})
it('should parse without encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support identity encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'identity')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support gzip encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support deflate encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'deflate')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should be case-insensitive', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'GZIP')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should 415 on unknown encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'nulls')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('000000000000', 'hex'))
test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)
})
})
})
function createManyParams (count) {
var str = ''
if (count === 0) {
return str
}
str += '0=0'
for (var i = 1; i < count; i++) {
var n = i.toString(36)
str += '&' + n + '=' + n
}
return str
}
function createApp (options) {
var app = express()
app.use(express.urlencoded(options))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send(String(req.headers['x-error-property']
? err[req.headers['x-error-property']]
: ('[' + err.type + '] ' + err.message)))
})
app.post('/', function (req, res) {
res.json(req.body)
})
return app
}
function expectKeyCount (count) {
return function (res) {
assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count)
}
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.head.js | test/app.head.js | 'use strict'
var express = require('../');
var request = require('supertest');
var assert = require('node:assert');
describe('HEAD', function(){
it('should default to GET', function(done){
var app = express();
app.get('/tobi', function(req, res){
// send() detects HEAD
res.send('tobi');
});
request(app)
.head('/tobi')
.expect(200, done);
})
it('should output the same headers as GET requests', function(done){
var app = express();
app.get('/tobi', function(req, res){
// send() detects HEAD
res.send('tobi');
});
request(app)
.head('/tobi')
.expect(200, function(err, res){
if (err) return done(err);
var headers = res.headers;
request(app)
.get('/tobi')
.expect(200, function(err, res){
if (err) return done(err);
delete headers.date;
delete res.headers.date;
assert.deepEqual(res.headers, headers);
done();
});
});
})
})
describe('app.head()', function(){
it('should override', function(done){
var app = express()
app.head('/tobi', function(req, res){
res.header('x-method', 'head')
res.end()
});
app.get('/tobi', function(req, res){
res.header('x-method', 'get')
res.send('tobi');
});
request(app)
.head('/tobi')
.expect('x-method', 'head')
.expect(200, done)
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.ip.js | test/req.ip.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.ip', function(){
describe('when X-Forwarded-For is present', function(){
describe('when "trust proxy" is enabled', function(){
it('should return the client addr', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res, next){
res.send(req.ip);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('client', done);
})
it('should return the addr after trusted proxy based on count', function (done) {
var app = express();
app.set('trust proxy', 2);
app.use(function(req, res, next){
res.send(req.ip);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('p1', done);
})
it('should return the addr after trusted proxy based on list', function (done) {
var app = express()
app.set('trust proxy', '10.0.0.1, 10.0.0.2, 127.0.0.1, ::1')
app.get('/', function (req, res) {
res.send(req.ip)
})
request(app)
.get('/')
.set('X-Forwarded-For', '10.0.0.2, 10.0.0.3, 10.0.0.1', '10.0.0.4')
.expect('10.0.0.3', done)
})
it('should return the addr after trusted proxy, from sub app', function (done) {
var app = express();
var sub = express();
app.set('trust proxy', 2);
app.use(sub);
sub.use(function (req, res, next) {
res.send(req.ip);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect(200, 'p1', done);
})
})
describe('when "trust proxy" is disabled', function(){
it('should return the remote address', function(done){
var app = express();
app.use(function(req, res, next){
res.send(req.ip);
});
var test = request(app).get('/')
test.set('X-Forwarded-For', 'client, p1, p2')
test.expect(200, getExpectedClientAddress(test._server), done);
})
})
})
describe('when X-Forwarded-For is not present', function(){
it('should return the remote address', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res, next){
res.send(req.ip);
});
var test = request(app).get('/')
test.expect(200, getExpectedClientAddress(test._server), done)
})
})
})
})
/**
* Get the local client address depending on AF_NET of server
*/
function getExpectedClientAddress(server) {
return server.address().address === '::'
? '::ffff:127.0.0.1'
: '127.0.0.1';
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.hostname.js | test/req.hostname.js | 'use strict'
var express = require('../')
, request = require('supertest')
describe('req', function(){
describe('.hostname', function(){
it('should return the Host when present', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.post('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
it('should strip port number', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.post('/')
.set('Host', 'example.com:3000')
.expect('example.com', done);
})
it('should return undefined otherwise', function(done){
var app = express();
app.use(function(req, res){
req.headers.host = null;
res.end(String(req.hostname));
});
request(app)
.post('/')
.expect('undefined', done);
})
it('should work with IPv6 Host', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.post('/')
.set('Host', '[::1]')
.expect('[::1]', done);
})
it('should work with IPv6 Host and port', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.post('/')
.set('Host', '[::1]:3000')
.expect('[::1]', done);
})
describe('when "trust proxy" is enabled', function(){
it('should respect X-Forwarded-Host', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com:3000')
.expect('example.com', done);
})
it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){
var app = express();
app.set('trust proxy', '10.0.0.1');
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com')
.expect('localhost', done);
})
it('should default to Host', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.get('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
describe('when multiple X-Forwarded-Host', function () {
it('should use the first value', function (done) {
var app = express()
app.enable('trust proxy')
app.use(function (req, res) {
res.send(req.hostname)
})
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com, foobar.com')
.expect(200, 'example.com', done)
})
it('should remove OWS around comma', function (done) {
var app = express()
app.enable('trust proxy')
app.use(function (req, res) {
res.send(req.hostname)
})
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com , foobar.com')
.expect(200, 'example.com', done)
})
it('should strip port number', function (done) {
var app = express()
app.enable('trust proxy')
app.use(function (req, res) {
res.send(req.hostname)
})
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888')
.expect(200, 'example.com', done)
})
})
})
describe('when "trust proxy" is disabled', function(){
it('should ignore X-Forwarded-Host', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.get('/')
.set('Host', 'localhost')
.set('X-Forwarded-Host', 'evil')
.expect('localhost', done);
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.query.js | test/req.query.js | 'use strict'
var assert = require('node:assert')
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.query', function(){
it('should default to {}', function(done){
var app = createApp();
request(app)
.get('/')
.expect(200, '{}', done);
});
it('should default to parse simple keys', function (done) {
var app = createApp();
request(app)
.get('/?user[name]=tj')
.expect(200, '{"user[name]":"tj"}', done);
});
describe('when "query parser" is extended', function () {
it('should parse complex keys', function (done) {
var app = createApp('extended');
request(app)
.get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!')
.expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done);
});
it('should parse parameters with dots', function (done) {
var app = createApp('extended');
request(app)
.get('/?user.name=tj')
.expect(200, '{"user.name":"tj"}', done);
});
});
describe('when "query parser" is simple', function () {
it('should not parse complex keys', function (done) {
var app = createApp('simple');
request(app)
.get('/?user%5Bname%5D=tj')
.expect(200, '{"user[name]":"tj"}', done);
});
});
describe('when "query parser" is a function', function () {
it('should parse using function', function (done) {
var app = createApp(function (str) {
return {'length': (str || '').length};
});
request(app)
.get('/?user%5Bname%5D=tj')
.expect(200, '{"length":17}', done);
});
});
describe('when "query parser" disabled', function () {
it('should not parse query', function (done) {
var app = createApp(false);
request(app)
.get('/?user%5Bname%5D=tj')
.expect(200, '{}', done);
});
});
describe('when "query parser" enabled', function () {
it('should not parse complex keys', function (done) {
var app = createApp(true);
request(app)
.get('/?user%5Bname%5D=tj')
.expect(200, '{"user[name]":"tj"}', done);
});
});
describe('when "query parser" an unknown value', function () {
it('should throw', function () {
assert.throws(createApp.bind(null, 'bogus'),
/unknown value.*query parser/)
});
});
})
})
function createApp(setting) {
var app = express();
if (setting !== undefined) {
app.set('query parser', setting);
}
app.use(function (req, res) {
res.send(req.query);
});
return app;
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/express.text.js | test/express.text.js | 'use strict'
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
const { Buffer } = require('node:buffer');
var express = require('..')
var request = require('supertest')
describe('express.text()', function () {
before(function () {
this.app = createApp()
})
it('should parse text/plain', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200, '"user is tobi"', done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.text())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'text/plain')
.set('Content-Length', '0')
.expect(200, '""', done)
})
it('should handle empty message-body', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'text/plain')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, '""', done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.text())
app.use(express.text())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200, '"user is tobi"', done)
})
describe('with defaultCharset option', function () {
it('should change default charset', function (done) {
var server = createApp({ defaultCharset: 'koi8-r' })
var test = request(server).post('/')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))
test.expect(200, '"name is нет"', done)
})
it('should honor content-type charset', function (done) {
var server = createApp({ defaultCharset: 'koi8-r' })
var test = request(server).post('/')
test.set('Content-Type', 'text/plain; charset=utf-8')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
})
describe('with limit option', function () {
it('should 413 when over limit with Content-Length', function (done) {
var buf = Buffer.alloc(1028, '.')
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'text/plain')
.set('Content-Length', '1028')
.send(buf.toString())
.expect(413, done)
})
it('should 413 when over limit with chunked encoding', function (done) {
var app = createApp({ limit: '1kb' })
var buf = Buffer.alloc(1028, '.')
var test = request(app).post('/')
test.set('Content-Type', 'text/plain')
test.set('Transfer-Encoding', 'chunked')
test.write(buf.toString())
test.expect(413, done)
})
it('should 413 when inflated body over limit', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex'))
test.expect(413, done)
})
it('should accept number of bytes', function (done) {
var buf = Buffer.alloc(1028, '.')
request(createApp({ limit: 1024 }))
.post('/')
.set('Content-Type', 'text/plain')
.send(buf.toString())
.expect(413, done)
})
it('should not change when options altered', function (done) {
var buf = Buffer.alloc(1028, '.')
var options = { limit: '1kb' }
var app = createApp(options)
options.limit = '100kb'
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send(buf.toString())
.expect(413, done)
})
it('should not hang response', function (done) {
var app = createApp({ limit: '8kb' })
var buf = Buffer.alloc(10240, '.')
var test = request(app).post('/')
test.set('Content-Type', 'text/plain')
test.write(buf)
test.write(buf)
test.write(buf)
test.expect(413, done)
})
it('should not error when inflating', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a1470404', 'hex'))
setTimeout(function () {
test.expect(413, done)
}, 100)
})
})
describe('with inflate option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ inflate: false })
})
it('should not accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))
test.expect(415, '[encoding.unsupported] content encoding unsupported', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ inflate: true })
})
it('should accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))
test.expect(200, '"name is 论"', done)
})
})
})
describe('with type option', function () {
describe('when "text/html"', function () {
before(function () {
this.app = createApp({ type: 'text/html' })
})
it('should parse for custom type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/html')
.send('<b>tobi</b>')
.expect(200, '"<b>tobi</b>"', done)
})
it('should ignore standard type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200, '', done)
})
})
describe('when ["text/html", "text/plain"]', function () {
before(function () {
this.app = createApp({ type: ['text/html', 'text/plain'] })
})
it('should parse "text/html"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/html')
.send('<b>tobi</b>')
.expect(200, '"<b>tobi</b>"', done)
})
it('should parse "text/plain"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/plain')
.send('tobi')
.expect(200, '"tobi"', done)
})
it('should ignore "text/xml"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/xml')
.send('<user>tobi</user>')
.expect(200, '', done)
})
})
describe('when a function', function () {
it('should parse when truthy value returned', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return req.headers['content-type'] === 'text/vnd.something'
}
request(app)
.post('/')
.set('Content-Type', 'text/vnd.something')
.send('user is tobi')
.expect(200, '"user is tobi"', done)
})
it('should work without content-type', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return true
}
var test = request(app).post('/')
test.write('user is tobi')
test.expect(200, '"user is tobi"', done)
})
it('should not invoke without a body', function (done) {
var app = createApp({ type: accept })
function accept (req) {
throw new Error('oops!')
}
request(app)
.get('/')
.expect(404, done)
})
})
})
describe('with verify option', function () {
it('should assert value is function', function () {
assert.throws(createApp.bind(null, { verify: 'lol' }),
/TypeError: option verify must be function/)
})
it('should error from verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x20) throw new Error('no leading space')
}
})
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send(' user is tobi')
.expect(403, '[entity.verify.failed] no leading space', done)
})
it('should allow custom codes', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x20) return
var err = new Error('no leading space')
err.status = 400
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send(' user is tobi')
.expect(400, '[entity.verify.failed] no leading space', done)
})
it('should allow pass-through', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x20) throw new Error('no leading space')
}
})
request(app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200, '"user is tobi"', done)
})
it('should 415 on unknown charset prior to verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
throw new Error('unexpected verify call')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'text/plain; charset=x-bogus')
test.write(Buffer.from('00000000', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)
})
})
describe('async local storage', function () {
before(function () {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(express.text())
app.use(function (req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
next()
})
app.use(function (err, req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.status(err.status || 500)
res.send('[' + err.type + '] ' + err.message)
})
app.post('/', function (req, res) {
res.json(req.body)
})
this.app = app
})
it('should persist store', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('"user is tobi"')
.end(done)
})
it('should persist store when unmatched content-type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/fizzbuzz')
.send('buzz')
.expect(200)
.expect('x-store-foo', 'bar')
.end(done)
})
it('should persist store when inflated', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))
test.expect(200)
test.expect('x-store-foo', 'bar')
test.expect('"name is 论"')
test.end(done)
})
it('should persist store when inflate error', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b0000', 'hex'))
test.expect(400)
test.expect('x-store-foo', 'bar')
test.end(done)
})
it('should persist store when limit exceeded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'text/plain')
.send('user is ' + Buffer.alloc(1024 * 100, '.').toString())
.expect(413)
.expect('x-store-foo', 'bar')
.end(done)
})
})
describe('charset', function () {
before(function () {
this.app = createApp()
})
it('should parse utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain; charset=utf-8')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should parse codepage charsets', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain; charset=koi8-r')
test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))
test.expect(200, '"name is нет"', done)
})
it('should parse when content-length != char length', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain; charset=utf-8')
test.set('Content-Length', '11')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should default to utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should 415 on unknown charset', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain; charset=x-bogus')
test.write(Buffer.from('00000000', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)
})
})
describe('encoding', function () {
before(function () {
this.app = createApp({ limit: '10kb' })
})
it('should parse without encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should support identity encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'identity')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should support gzip encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should support deflate encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'deflate')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('789ccb4bcc4d55c82c5678b16e17001a6f050e', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should be case-insensitive', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'GZIP')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))
test.expect(200, '"name is 论"', done)
})
it('should 415 on unknown encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'nulls')
test.set('Content-Type', 'text/plain')
test.write(Buffer.from('000000000000', 'hex'))
test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)
})
})
})
function createApp (options) {
var app = express()
app.use(express.text(options))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send(String(req.headers['x-error-property']
? err[req.headers['x-error-property']]
: ('[' + err.type + '] ' + err.message)))
})
app.post('/', function (req, res) {
res.json(req.body)
})
return app
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.response.js | test/app.response.js | 'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.response', function(){
it('should extend the response prototype', function(done){
var app = express();
app.response.shout = function(str){
this.send(str.toUpperCase());
};
app.use(function(req, res){
res.shout('hey');
});
request(app)
.get('/')
.expect('HEY', done);
})
it('should only extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has no method)/, cb)
})
it('should inherit to sub apps', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'FOO', cb)
})
it('should allow sub app to override', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
})
it('should not pollute parent app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/sub/foo', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
request(app1)
.get('/sub/foo')
.expect(200, 'FOO', cb)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.use.js | test/app.use.js | 'use strict'
var after = require('after');
var assert = require('node:assert')
var express = require('..');
var request = require('supertest');
describe('app', function(){
it('should emit "mount" when mounted', function(done){
var blog = express()
, app = express();
blog.on('mount', function(arg){
assert.strictEqual(arg, app)
done();
});
app.use(blog);
})
describe('.use(app)', function(){
it('should mount the app', function(done){
var blog = express()
, app = express();
blog.get('/blog', function(req, res){
res.end('blog');
});
app.use(blog);
request(app)
.get('/blog')
.expect('blog', done);
})
it('should support mount-points', function(done){
var blog = express()
, forum = express()
, app = express();
var cb = after(2, done)
blog.get('/', function(req, res){
res.end('blog');
});
forum.get('/', function(req, res){
res.end('forum');
});
app.use('/blog', blog);
app.use('/forum', forum);
request(app)
.get('/blog')
.expect(200, 'blog', cb)
request(app)
.get('/forum')
.expect(200, 'forum', cb)
})
it('should set the child\'s .parent', function(){
var blog = express()
, app = express();
app.use('/blog', blog);
assert.strictEqual(blog.parent, app)
})
it('should support dynamic routes', function(done){
var blog = express()
, app = express();
blog.get('/', function(req, res){
res.end('success');
});
app.use('/post/:article', blog);
request(app)
.get('/post/once-upon-a-time')
.expect('success', done);
})
it('should support mounted app anywhere', function(done){
var cb = after(3, done);
var blog = express()
, other = express()
, app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
blog.get('/', function(req, res){
res.end('success');
});
blog.once('mount', function (parent) {
assert.strictEqual(parent, app)
cb();
});
other.once('mount', function (parent) {
assert.strictEqual(parent, app)
cb();
});
app.use('/post/:article', fn1, other, fn2, blog);
request(app)
.get('/post/once-upon-a-time')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('success', cb);
})
})
describe('.use(middleware)', function(){
it('should accept multiple arguments', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
app.use(fn1, fn2, function fn3(req, res) {
res.setHeader('x-fn-3', 'hit');
res.end();
});
request(app)
.get('/')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should invoke middleware for all requests', function (done) {
var app = express();
var cb = after(3, done);
app.use(function (req, res) {
res.send('saw ' + req.method + ' ' + req.url);
});
request(app)
.get('/')
.expect(200, 'saw GET /', cb);
request(app)
.options('/')
.expect(200, 'saw OPTIONS /', cb);
request(app)
.post('/foo')
.expect(200, 'saw POST /foo', cb);
})
it('should accept array of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use([fn1, fn2, fn3]);
request(app)
.get('/')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should accept multiple arrays of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use([fn1, fn2], [fn3]);
request(app)
.get('/')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should accept nested arrays of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use([[fn1], fn2], [fn3]);
request(app)
.get('/')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
})
describe('.use(path, middleware)', function(){
it('should require middleware', function () {
var app = express()
assert.throws(function () { app.use('/') }, 'TypeError: app.use() requires a middleware function')
})
it('should reject string as middleware', function () {
var app = express()
assert.throws(function () { app.use('/', 'foo') }, /argument handler must be a function/)
})
it('should reject number as middleware', function () {
var app = express()
assert.throws(function () { app.use('/', 42) }, /argument handler must be a function/)
})
it('should reject null as middleware', function () {
var app = express()
assert.throws(function () { app.use('/', null) }, /argument handler must be a function/)
})
it('should reject Date as middleware', function () {
var app = express()
assert.throws(function () { app.use('/', new Date()) }, /argument handler must be a function/)
})
it('should strip path from req.url', function (done) {
var app = express();
app.use('/foo', function (req, res) {
res.send('saw ' + req.method + ' ' + req.url);
});
request(app)
.get('/foo/bar')
.expect(200, 'saw GET /bar', done);
})
it('should accept multiple arguments', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
app.use('/foo', fn1, fn2, function fn3(req, res) {
res.setHeader('x-fn-3', 'hit');
res.end();
});
request(app)
.get('/foo')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should invoke middleware for all requests starting with path', function (done) {
var app = express();
var cb = after(3, done);
app.use('/foo', function (req, res) {
res.send('saw ' + req.method + ' ' + req.url);
});
request(app)
.get('/')
.expect(404, cb);
request(app)
.post('/foo')
.expect(200, 'saw POST /', cb);
request(app)
.post('/foo/bar')
.expect(200, 'saw POST /bar', cb);
})
it('should work if path has trailing slash', function (done) {
var app = express();
var cb = after(3, done);
app.use('/foo/', function (req, res) {
res.send('saw ' + req.method + ' ' + req.url);
});
request(app)
.get('/')
.expect(404, cb);
request(app)
.post('/foo')
.expect(200, 'saw POST /', cb);
request(app)
.post('/foo/bar')
.expect(200, 'saw POST /bar', cb);
})
it('should accept array of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use('/foo', [fn1, fn2, fn3]);
request(app)
.get('/foo')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should accept multiple arrays of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use('/foo', [fn1, fn2], [fn3]);
request(app)
.get('/foo')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should accept nested arrays of middleware', function (done) {
var app = express();
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.end();
}
app.use('/foo', [fn1, [fn2]], [fn3]);
request(app)
.get('/foo')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, done);
})
it('should support array of paths', function (done) {
var app = express();
var cb = after(3, done);
app.use(['/foo/', '/bar'], function (req, res) {
res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl);
});
request(app)
.get('/')
.expect(404, cb);
request(app)
.get('/foo')
.expect(200, 'saw GET / through /foo', cb);
request(app)
.get('/bar')
.expect(200, 'saw GET / through /bar', cb);
})
it('should support array of paths with middleware array', function (done) {
var app = express();
var cb = after(2, done);
function fn1(req, res, next) {
res.setHeader('x-fn-1', 'hit');
next();
}
function fn2(req, res, next) {
res.setHeader('x-fn-2', 'hit');
next();
}
function fn3(req, res, next) {
res.setHeader('x-fn-3', 'hit');
res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl);
}
app.use(['/foo/', '/bar'], [[fn1], fn2], [fn3]);
request(app)
.get('/foo')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, 'saw GET / through /foo', cb);
request(app)
.get('/bar')
.expect('x-fn-1', 'hit')
.expect('x-fn-2', 'hit')
.expect('x-fn-3', 'hit')
.expect(200, 'saw GET / through /bar', cb);
})
it('should support regexp path', function (done) {
var app = express();
var cb = after(4, done);
app.use(/^\/[a-z]oo/, function (req, res) {
res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl);
});
request(app)
.get('/')
.expect(404, cb);
request(app)
.get('/foo')
.expect(200, 'saw GET / through /foo', cb);
request(app)
.get('/zoo/bear')
.expect(200, 'saw GET /bear through /zoo/bear', cb);
request(app)
.get('/get/zoo')
.expect(404, cb);
})
it('should support empty string path', function (done) {
var app = express();
app.use('', function (req, res) {
res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl);
});
request(app)
.get('/')
.expect(200, 'saw GET / through /', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.jsonp.js | test/res.jsonp.js | 'use strict'
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
var utils = require('./support/utils');
describe('res', function(){
describe('.jsonp(object)', function(){
it('should respond with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should use first callback parameter with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something&callback=somethingelse')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should ignore object callback parameter with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback[a]=something')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"count":1}', done)
})
it('should allow renaming callback', function(done){
var app = express();
app.set('jsonp callback name', 'clb');
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?clb=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should allow []', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=callbacks[123]')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /callbacks\[123\]\(\{"count":1\}\);/, done);
})
it('should disallow arbitrary js', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({});
});
request(app)
.get('/?callback=foo;bar()')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foobar\(\{\}\);/, done);
})
it('should escape utf whitespace', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ str: '\u2028 \u2029 woot' });
});
request(app)
.get('/?callback=foo')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foo\(\{"str":"\\u2028 \\u2029 woot"\}\);/, done);
});
it('should not escape utf whitespace for json fallback', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ str: '\u2028 \u2029 woot' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"str":"\u2028 \u2029 woot"}', done);
});
it('should include security header and prologue', function (done) {
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect('X-Content-Type-Options', 'nosniff')
.expect(200, /^\/\*\*\//, done);
})
it('should not override previous Content-Types with no callback', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/vnd.example+json; charset=utf-8')
.expect(utils.shouldNotHaveHeader('X-Content-Type-Options'))
.expect(200, '{"hello":"world"}', done);
})
it('should override previous Content-Types with callback', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect('X-Content-Type-Options', 'nosniff')
.expect(200, /cb\(\{"hello":"world"\}\);$/, done);
})
describe('when given undefined', function () {
it('should invoke callback with no arguments', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(undefined)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\)/, done)
})
})
describe('when given null', function () {
it('should invoke callback with null', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(null)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(null\)/, done)
})
})
describe('when given a string', function () {
it('should invoke callback with a string', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp('tobi')
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\("tobi"\)/, done)
})
})
describe('when given a number', function () {
it('should invoke callback with a number', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(42)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(42\)/, done)
})
})
describe('when given an array', function () {
it('should invoke callback with an array', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(['foo', 'bar', 'baz'])
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\["foo","bar","baz"\]\)/, done)
})
})
describe('when given an object', function () {
it('should invoke callback with an object', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp({ name: 'tobi' })
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\{"name":"tobi"\}\)/, done)
})
})
describe('"json escape" setting', function () {
it('should be undefined by default', function () {
var app = express()
assert.strictEqual(app.get('json escape'), undefined)
})
it('should unicode escape HTML-sniffing characters', function (done) {
var app = express()
app.enable('json escape')
app.use(function (req, res) {
res.jsonp({ '&': '\u2028<script>\u2029' })
})
request(app)
.get('/?callback=foo')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foo\({"\\u0026":"\\u2028\\u003cscript\\u003e\\u2029"}\)/, done)
})
it('should not break undefined escape', function (done) {
var app = express()
app.enable('json escape')
app.use(function (req, res) {
res.jsonp(undefined)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\)/, done)
})
})
describe('"json replacer" setting', function(){
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json replacer', function(key, val){
return key[0] === '_'
? undefined
: val;
});
app.use(function(req, res){
res.jsonp({ name: 'tobi', _id: 12345 });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"name":"tobi"}', done)
})
})
describe('"json spaces" setting', function(){
it('should be undefined by default', function(){
var app = express();
assert(undefined === app.get('json spaces'));
})
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json spaces', 2);
app.use(function(req, res){
res.jsonp({ name: 'tobi', age: 2 });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{\n "name": "tobi",\n "age": 2\n}', done)
})
})
})
it('should not override previous Content-Types', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});
request(app)
.get('/')
.expect('content-type', 'application/vnd.example+json; charset=utf-8')
.expect(200, '{"hello":"world"}', done)
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.js | test/app.js | 'use strict'
var assert = require('node:assert')
var express = require('..')
var request = require('supertest')
describe('app', function(){
it('should inherit from event emitter', function(done){
var app = express();
app.on('foo', done);
app.emit('foo');
})
it('should be callable', function(){
var app = express();
assert.equal(typeof app, 'function');
})
it('should 404 without routes', function(done){
request(express())
.get('/')
.expect(404, done);
})
})
describe('app.parent', function(){
it('should return the parent when mounted', function(){
var app = express()
, blog = express()
, blogAdmin = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
assert(!app.parent, 'app.parent');
assert.strictEqual(blog.parent, app)
assert.strictEqual(blogAdmin.parent, blog)
})
})
describe('app.mountpath', function(){
it('should return the mounted path', function(){
var admin = express();
var app = express();
var blog = express();
var fallback = express();
app.use('/blog', blog);
app.use(fallback);
blog.use('/admin', admin);
assert.strictEqual(admin.mountpath, '/admin')
assert.strictEqual(app.mountpath, '/')
assert.strictEqual(blog.mountpath, '/blog')
assert.strictEqual(fallback.mountpath, '/')
})
})
describe('app.path()', function(){
it('should return the canonical', function(){
var app = express()
, blog = express()
, blogAdmin = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
assert.strictEqual(app.path(), '')
assert.strictEqual(blog.path(), '/blog')
assert.strictEqual(blogAdmin.path(), '/blog/admin')
})
})
describe('in development', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = 'development'
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should disable "view cache"', function(){
var app = express();
assert.ok(!app.enabled('view cache'))
})
})
describe('in production', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = 'production'
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should enable "view cache"', function(){
var app = express();
assert.ok(app.enabled('view cache'))
})
})
describe('without NODE_ENV', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = ''
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should default to development', function(){
var app = express();
assert.strictEqual(app.get('env'), 'development')
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/exports.js | test/exports.js | 'use strict'
var assert = require('node:assert')
var express = require('../');
var request = require('supertest');
describe('exports', function(){
it('should expose Router', function(){
assert.strictEqual(typeof express.Router, 'function')
})
it('should expose json middleware', function () {
assert.equal(typeof express.json, 'function')
assert.equal(express.json.length, 1)
})
it('should expose raw middleware', function () {
assert.equal(typeof express.raw, 'function')
assert.equal(express.raw.length, 1)
})
it('should expose static middleware', function () {
assert.equal(typeof express.static, 'function')
assert.equal(express.static.length, 2)
})
it('should expose text middleware', function () {
assert.equal(typeof express.text, 'function')
assert.equal(express.text.length, 1)
})
it('should expose urlencoded middleware', function () {
assert.equal(typeof express.urlencoded, 'function')
assert.equal(express.urlencoded.length, 1)
})
it('should expose the application prototype', function(){
assert.strictEqual(typeof express.application, 'object')
assert.strictEqual(typeof express.application.set, 'function')
})
it('should expose the request prototype', function(){
assert.strictEqual(typeof express.request, 'object')
assert.strictEqual(typeof express.request.accepts, 'function')
})
it('should expose the response prototype', function(){
assert.strictEqual(typeof express.response, 'object')
assert.strictEqual(typeof express.response.send, 'function')
})
it('should permit modifying the .application prototype', function(){
express.application.foo = function(){ return 'bar'; };
assert.strictEqual(express().foo(), 'bar')
})
it('should permit modifying the .request prototype', function(done){
express.request.foo = function(){ return 'bar'; };
var app = express();
app.use(function(req, res, next){
res.end(req.foo());
});
request(app)
.get('/')
.expect('bar', done);
})
it('should permit modifying the .response prototype', function(done){
express.response.foo = function(){ this.send('bar'); };
var app = express();
app.use(function(req, res, next){
res.foo();
});
request(app)
.get('/')
.expect('bar', done);
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/config.js | test/config.js | 'use strict'
var assert = require('node:assert');
var express = require('..');
describe('config', function () {
describe('.set()', function () {
it('should set a value', function () {
var app = express();
app.set('foo', 'bar');
assert.equal(app.get('foo'), 'bar');
})
it('should set prototype values', function () {
var app = express()
app.set('hasOwnProperty', 42)
assert.strictEqual(app.get('hasOwnProperty'), 42)
})
it('should return the app', function () {
var app = express();
assert.equal(app.set('foo', 'bar'), app);
})
it('should return the app when undefined', function () {
var app = express();
assert.equal(app.set('foo', undefined), app);
})
it('should return set value', function () {
var app = express()
app.set('foo', 'bar')
assert.strictEqual(app.set('foo'), 'bar')
})
it('should return undefined for prototype values', function () {
var app = express()
assert.strictEqual(app.set('hasOwnProperty'), undefined)
})
describe('"etag"', function(){
it('should throw on bad value', function(){
var app = express();
assert.throws(app.set.bind(app, 'etag', 42), /unknown value/);
})
it('should set "etag fn"', function(){
var app = express()
var fn = function(){}
app.set('etag', fn)
assert.equal(app.get('etag fn'), fn)
})
})
describe('"trust proxy"', function(){
it('should set "trust proxy fn"', function(){
var app = express()
var fn = function(){}
app.set('trust proxy', fn)
assert.equal(app.get('trust proxy fn'), fn)
})
})
})
describe('.get()', function(){
it('should return undefined when unset', function(){
var app = express();
assert.strictEqual(app.get('foo'), undefined);
})
it('should return undefined for prototype values', function () {
var app = express()
assert.strictEqual(app.get('hasOwnProperty'), undefined)
})
it('should otherwise return the value', function(){
var app = express();
app.set('foo', 'bar');
assert.equal(app.get('foo'), 'bar');
})
describe('when mounted', function(){
it('should default to the parent app', function(){
var app = express();
var blog = express();
app.set('title', 'Express');
app.use(blog);
assert.equal(blog.get('title'), 'Express');
})
it('should given precedence to the child', function(){
var app = express();
var blog = express();
app.use(blog);
app.set('title', 'Express');
blog.set('title', 'Some Blog');
assert.equal(blog.get('title'), 'Some Blog');
})
it('should inherit "trust proxy" setting', function () {
var app = express();
var blog = express();
function fn() { return false }
app.set('trust proxy', fn);
assert.equal(app.get('trust proxy'), fn);
assert.equal(app.get('trust proxy fn'), fn);
app.use(blog);
assert.equal(blog.get('trust proxy'), fn);
assert.equal(blog.get('trust proxy fn'), fn);
})
it('should prefer child "trust proxy" setting', function () {
var app = express();
var blog = express();
function fn1() { return false }
function fn2() { return true }
app.set('trust proxy', fn1);
assert.equal(app.get('trust proxy'), fn1);
assert.equal(app.get('trust proxy fn'), fn1);
blog.set('trust proxy', fn2);
assert.equal(blog.get('trust proxy'), fn2);
assert.equal(blog.get('trust proxy fn'), fn2);
app.use(blog);
assert.equal(app.get('trust proxy'), fn1);
assert.equal(app.get('trust proxy fn'), fn1);
assert.equal(blog.get('trust proxy'), fn2);
assert.equal(blog.get('trust proxy fn'), fn2);
})
})
})
describe('.enable()', function(){
it('should set the value to true', function(){
var app = express();
assert.equal(app.enable('tobi'), app);
assert.strictEqual(app.get('tobi'), true);
})
it('should set prototype values', function () {
var app = express()
app.enable('hasOwnProperty')
assert.strictEqual(app.get('hasOwnProperty'), true)
})
})
describe('.disable()', function(){
it('should set the value to false', function(){
var app = express();
assert.equal(app.disable('tobi'), app);
assert.strictEqual(app.get('tobi'), false);
})
it('should set prototype values', function () {
var app = express()
app.disable('hasOwnProperty')
assert.strictEqual(app.get('hasOwnProperty'), false)
})
})
describe('.enabled()', function(){
it('should default to false', function(){
var app = express();
assert.strictEqual(app.enabled('foo'), false);
})
it('should return true when set', function(){
var app = express();
app.set('foo', 'bar');
assert.strictEqual(app.enabled('foo'), true);
})
it('should default to false for prototype values', function () {
var app = express()
assert.strictEqual(app.enabled('hasOwnProperty'), false)
})
})
describe('.disabled()', function(){
it('should default to true', function(){
var app = express();
assert.strictEqual(app.disabled('foo'), true);
})
it('should return false when set', function(){
var app = express();
app.set('foo', 'bar');
assert.strictEqual(app.disabled('foo'), false);
})
it('should default to true for prototype values', function () {
var app = express()
assert.strictEqual(app.disabled('hasOwnProperty'), true)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.sendFile.js | test/res.sendFile.js | 'use strict'
var after = require('after');
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
const { Buffer } = require('node:buffer');
var express = require('../')
, request = require('supertest')
var onFinished = require('on-finished');
var path = require('node:path');
var fixtures = path.join(__dirname, 'fixtures');
var utils = require('./support/utils');
describe('res', function(){
describe('.sendFile(path)', function () {
it('should error missing path', function (done) {
var app = createApp();
request(app)
.get('/')
.expect(500, /path.*required/, done);
});
it('should error for non-string path', function (done) {
var app = createApp(42)
request(app)
.get('/')
.expect(500, /TypeError: path must be a string to res.sendFile/, done)
})
it('should error for non-absolute path', function (done) {
var app = createApp('name.txt')
request(app)
.get('/')
.expect(500, /TypeError: path must be absolute/, done)
})
it('should transfer a file', function (done) {
var app = createApp(path.resolve(fixtures, 'name.txt'));
request(app)
.get('/')
.expect(200, 'tobi', done);
});
it('should transfer a file with special characters in string', function (done) {
var app = createApp(path.resolve(fixtures, '% of dogs.txt'));
request(app)
.get('/')
.expect(200, '20%', done);
});
it('should include ETag', function (done) {
var app = createApp(path.resolve(fixtures, 'name.txt'));
request(app)
.get('/')
.expect('ETag', /^(?:W\/)?"[^"]+"$/)
.expect(200, 'tobi', done);
});
it('should 304 when ETag matches', function (done) {
var app = createApp(path.resolve(fixtures, 'name.txt'));
request(app)
.get('/')
.expect('ETag', /^(?:W\/)?"[^"]+"$/)
.expect(200, 'tobi', function (err, res) {
if (err) return done(err);
var etag = res.headers.etag;
request(app)
.get('/')
.set('If-None-Match', etag)
.expect(304, done);
});
});
it('should disable the ETag function if requested', function (done) {
var app = createApp(path.resolve(fixtures, 'name.txt')).disable('etag');
request(app)
.get('/')
.expect(handleHeaders)
.expect(200, done);
function handleHeaders (res) {
assert(res.headers.etag === undefined);
}
});
it('should 404 for directory', function (done) {
var app = createApp(path.resolve(fixtures, 'blog'));
request(app)
.get('/')
.expect(404, done);
});
it('should 404 when not found', function (done) {
var app = createApp(path.resolve(fixtures, 'does-no-exist'));
app.use(function (req, res) {
res.statusCode = 200;
res.send('no!');
});
request(app)
.get('/')
.expect(404, done);
});
it('should send cache-control by default', function (done) {
var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))
request(app)
.get('/')
.expect('Cache-Control', 'public, max-age=0')
.expect(200, done)
})
it('should not serve dotfiles by default', function (done) {
var app = createApp(path.resolve(__dirname, 'fixtures/.name'))
request(app)
.get('/')
.expect(404, done)
})
it('should not override manual content-types', function (done) {
var app = express();
app.use(function (req, res) {
res.contentType('application/x-bogus');
res.sendFile(path.resolve(fixtures, 'name.txt'));
});
request(app)
.get('/')
.expect('Content-Type', 'application/x-bogus')
.end(done);
})
it('should not error if the client aborts', function (done) {
var app = express();
var cb = after(2, done)
var error = null
app.use(function (req, res) {
setImmediate(function () {
res.sendFile(path.resolve(fixtures, 'name.txt'));
setTimeout(function () {
cb(error)
}, 10)
})
test.req.abort()
});
app.use(function (err, req, res, next) {
error = err
next(err)
});
var server = app.listen()
var test = request(server).get('/')
test.end(function (err) {
assert.ok(err)
server.close(cb)
})
})
})
describe('.sendFile(path, fn)', function () {
it('should invoke the callback when complete', function (done) {
var cb = after(2, done);
var app = createApp(path.resolve(fixtures, 'name.txt'), cb);
request(app)
.get('/')
.expect(200, cb);
})
it('should invoke the callback when client aborts', function (done) {
var cb = after(2, done)
var app = express();
app.use(function (req, res) {
setImmediate(function () {
res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {
assert.ok(err)
assert.strictEqual(err.code, 'ECONNABORTED')
cb()
});
});
test.req.abort()
});
var server = app.listen()
var test = request(server).get('/')
test.end(function (err) {
assert.ok(err)
server.close(cb)
})
})
it('should invoke the callback when client already aborted', function (done) {
var cb = after(2, done)
var app = express();
app.use(function (req, res) {
onFinished(res, function () {
res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {
assert.ok(err)
assert.strictEqual(err.code, 'ECONNABORTED')
cb()
});
});
test.req.abort()
});
var server = app.listen()
var test = request(server).get('/')
test.end(function (err) {
assert.ok(err)
server.close(cb)
})
})
it('should invoke the callback without error when HEAD', function (done) {
var app = express();
var cb = after(2, done);
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'name.txt'), cb);
});
request(app)
.head('/')
.expect(200, cb);
});
it('should invoke the callback without error when 304', function (done) {
var app = express();
var cb = after(3, done);
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'name.txt'), cb);
});
request(app)
.get('/')
.expect('ETag', /^(?:W\/)?"[^"]+"$/)
.expect(200, 'tobi', function (err, res) {
if (err) return cb(err);
var etag = res.headers.etag;
request(app)
.get('/')
.set('If-None-Match', etag)
.expect(304, cb);
});
});
it('should invoke the callback on 404', function(done){
var app = express();
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {
res.send(err ? 'got ' + err.status + ' error' : 'no error')
});
});
request(app)
.get('/')
.expect(200, 'got 404 error', done)
})
describe('async local storage', function () {
it('should persist store', function (done) {
var app = express()
var cb = after(2, done)
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {
if (err) return cb(err)
var local = req.asyncLocalStorage.getStore()
assert.strictEqual(local.foo, 'bar')
cb()
})
})
request(app)
.get('/')
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect(200, 'tobi', cb)
})
it('should persist store on error', function (done) {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.send(err ? 'got ' + err.status + ' error' : 'no error')
})
})
request(app)
.get('/')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('got 404 error')
.end(done)
})
})
})
describe('.sendFile(path, options)', function () {
it('should pass options to send module', function (done) {
request(createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 }))
.get('/')
.expect(200, 'to', done)
})
describe('with "acceptRanges" option', function () {
describe('when true', function () {
it('should advertise byte range accepted', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'nums.txt'), {
acceptRanges: true
})
})
request(app)
.get('/')
.expect(200)
.expect('Accept-Ranges', 'bytes')
.expect('123456789')
.end(done)
})
it('should respond to range request', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'nums.txt'), {
acceptRanges: true
})
})
request(app)
.get('/')
.set('Range', 'bytes=0-4')
.expect(206, '12345', done)
})
})
describe('when false', function () {
it('should not advertise accept-ranges', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'nums.txt'), {
acceptRanges: false
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldNotHaveHeader('Accept-Ranges'))
.end(done)
})
it('should not honor range requests', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'nums.txt'), {
acceptRanges: false
})
})
request(app)
.get('/')
.set('Range', 'bytes=0-4')
.expect(200, '123456789', done)
})
})
})
describe('with "cacheControl" option', function () {
describe('when true', function () {
it('should send cache-control header', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
cacheControl: true
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=0')
.end(done)
})
})
describe('when false', function () {
it('should not send cache-control header', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
cacheControl: false
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldNotHaveHeader('Cache-Control'))
.end(done)
})
})
})
describe('with "dotfiles" option', function () {
describe('when "allow"', function () {
it('should allow dotfiles', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, '.name'), {
dotfiles: 'allow'
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldHaveBody(Buffer.from('tobi')))
.end(done)
})
})
describe('when "deny"', function () {
it('should deny dotfiles', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, '.name'), {
dotfiles: 'deny'
})
})
request(app)
.get('/')
.expect(403)
.expect(/Forbidden/)
.end(done)
})
})
describe('when "ignore"', function () {
it('should ignore dotfiles', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, '.name'), {
dotfiles: 'ignore'
})
})
request(app)
.get('/')
.expect(404)
.expect(/Not Found/)
.end(done)
})
})
})
describe('with "headers" option', function () {
it('should set headers on response', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
headers: {
'X-Foo': 'Bar',
'X-Bar': 'Foo'
}
})
})
request(app)
.get('/')
.expect(200)
.expect('X-Foo', 'Bar')
.expect('X-Bar', 'Foo')
.end(done)
})
it('should use last header when duplicated', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
headers: {
'X-Foo': 'Bar',
'x-foo': 'bar'
}
})
})
request(app)
.get('/')
.expect(200)
.expect('X-Foo', 'bar')
.end(done)
})
it('should override Content-Type', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
headers: {
'Content-Type': 'text/x-custom'
}
})
})
request(app)
.get('/')
.expect(200)
.expect('Content-Type', 'text/x-custom')
.end(done)
})
it('should not set headers on 404', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'does-not-exist'), {
headers: {
'X-Foo': 'Bar'
}
})
})
request(app)
.get('/')
.expect(404)
.expect(utils.shouldNotHaveHeader('X-Foo'))
.end(done)
})
})
describe('with "immutable" option', function () {
describe('when true', function () {
it('should send cache-control header with immutable', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
immutable: true
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=0, immutable')
.end(done)
})
})
describe('when false', function () {
it('should not send cache-control header with immutable', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
immutable: false
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=0')
.end(done)
})
})
})
describe('with "lastModified" option', function () {
describe('when true', function () {
it('should send last-modified header', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
lastModified: true
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldHaveHeader('Last-Modified'))
.end(done)
})
it('should conditionally respond with if-modified-since', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
lastModified: true
})
})
request(app)
.get('/')
.set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString()))
.expect(304, done)
})
})
describe('when false', function () {
it('should not have last-modified header', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
lastModified: false
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldNotHaveHeader('Last-Modified'))
.end(done)
})
it('should not honor if-modified-since', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
lastModified: false
})
})
request(app)
.get('/')
.set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString()))
.expect(200)
.expect(utils.shouldNotHaveHeader('Last-Modified'))
.end(done)
})
})
})
describe('with "maxAge" option', function () {
it('should set cache-control max-age to milliseconds', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: 20000
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=20')
.end(done)
})
it('should cap cache-control max-age to 1 year', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: 99999999999
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=31536000')
.end(done)
})
it('should min cache-control max-age to 0', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: -20000
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=0')
.end(done)
})
it('should floor cache-control max-age', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: 21911.23
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=21')
.end(done)
})
describe('when cacheControl: false', function () {
it('should not send cache-control', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
cacheControl: false,
maxAge: 20000
})
})
request(app)
.get('/')
.expect(200)
.expect(utils.shouldNotHaveHeader('Cache-Control'))
.end(done)
})
})
describe('when string', function () {
it('should accept plain number as milliseconds', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: '20000'
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=20')
.end(done)
})
it('should accept suffix "s" for seconds', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: '20s'
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=20')
.end(done)
})
it('should accept suffix "m" for minutes', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: '20m'
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=1200')
.end(done)
})
it('should accept suffix "d" for days', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile(path.resolve(fixtures, 'user.html'), {
maxAge: '20d'
})
})
request(app)
.get('/')
.expect(200)
.expect('Cache-Control', 'public, max-age=1728000')
.end(done)
})
})
})
describe('with "root" option', function () {
it('should allow relative path', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile('name.txt', {
root: fixtures
})
})
request(app)
.get('/')
.expect(200, 'tobi', done)
})
it('should allow up within root', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile('fake/../name.txt', {
root: fixtures
})
})
request(app)
.get('/')
.expect(200, 'tobi', done)
})
it('should reject up outside root', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile('..' + path.sep + path.relative(path.dirname(fixtures), path.join(fixtures, 'name.txt')), {
root: fixtures
})
})
request(app)
.get('/')
.expect(403, done)
})
it('should reject reading outside root', function (done) {
var app = express()
app.use(function (req, res) {
res.sendFile('../name.txt', {
root: fixtures
})
})
request(app)
.get('/')
.expect(403, done)
})
})
})
})
function createApp(path, options, fn) {
var app = express();
app.use(function (req, res) {
res.sendFile(path, options, fn);
});
return app;
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.secure.js | test/req.secure.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.secure', function(){
describe('when X-Forwarded-Proto is missing', function(){
it('should return false when http', function(done){
var app = express();
app.get('/', function(req, res){
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.expect('no', done)
})
})
})
describe('.secure', function(){
describe('when X-Forwarded-Proto is present', function(){
it('should return false when http', function(done){
var app = express();
app.get('/', function(req, res){
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('no', done)
})
it('should return true when "trust proxy" is enabled', function(done){
var app = express();
app.enable('trust proxy');
app.get('/', function(req, res){
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('yes', done)
})
it('should return false when initial proxy is http', function(done){
var app = express();
app.enable('trust proxy');
app.get('/', function(req, res){
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'http, https')
.expect('no', done)
})
it('should return true when initial proxy is https', function(done){
var app = express();
app.enable('trust proxy');
app.get('/', function(req, res){
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https, http')
.expect('yes', done)
})
describe('when "trust proxy" trusting hop count', function () {
it('should respect X-Forwarded-Proto', function (done) {
var app = express();
app.set('trust proxy', 1);
app.get('/', function (req, res) {
res.send(req.secure ? 'yes' : 'no');
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('yes', done)
})
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/middleware.basic.js | test/middleware.basic.js | 'use strict'
var assert = require('node:assert')
var express = require('../');
var request = require('supertest');
describe('middleware', function(){
describe('.next()', function(){
it('should behave like connect', function(done){
var app = express()
, calls = [];
app.use(function(req, res, next){
calls.push('one');
next();
});
app.use(function(req, res, next){
calls.push('two');
next();
});
app.use(function(req, res){
var buf = '';
res.setHeader('Content-Type', 'application/json');
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
res.end(buf);
});
});
request(app)
.get('/')
.set('Content-Type', 'application/json')
.send('{"foo":"bar"}')
.expect('Content-Type', 'application/json')
.expect(function () { assert.deepEqual(calls, ['one', 'two']) })
.expect(200, '{"foo":"bar"}', done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.json.js | test/res.json.js | 'use strict'
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
describe('res', function(){
describe('.json(object)', function(){
it('should not support jsonp callbacks', function(done){
var app = express();
app.use(function(req, res){
res.json({ foo: 'bar' });
});
request(app)
.get('/?callback=foo')
.expect('{"foo":"bar"}', done);
})
it('should not override previous Content-Types', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.json({ hello: 'world' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/vnd.example+json; charset=utf-8')
.expect(200, '{"hello":"world"}', done);
})
describe('when given primitives', function(){
it('should respond with json for null', function(done){
var app = express();
app.use(function(req, res){
res.json(null);
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, 'null', done)
})
it('should respond with json for Number', function(done){
var app = express();
app.use(function(req, res){
res.json(300);
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '300', done)
})
it('should respond with json for String', function(done){
var app = express();
app.use(function(req, res){
res.json('str');
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '"str"', done)
})
})
describe('when given an array', function(){
it('should respond with json', function(done){
var app = express();
app.use(function(req, res){
res.json(['foo', 'bar', 'baz']);
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '["foo","bar","baz"]', done)
})
})
describe('when given an object', function(){
it('should respond with json', function(done){
var app = express();
app.use(function(req, res){
res.json({ name: 'tobi' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"name":"tobi"}', done)
})
})
describe('"json escape" setting', function () {
it('should be undefined by default', function () {
var app = express()
assert.strictEqual(app.get('json escape'), undefined)
})
it('should unicode escape HTML-sniffing characters', function (done) {
var app = express()
app.enable('json escape')
app.use(function (req, res) {
res.json({ '&': '<script>' })
})
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"\\u0026":"\\u003cscript\\u003e"}', done)
})
it('should not break undefined escape', function (done) {
var app = express()
app.enable('json escape')
app.use(function (req, res) {
res.json(undefined)
})
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '', done)
})
})
describe('"json replacer" setting', function(){
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json replacer', function(key, val){
return key[0] === '_'
? undefined
: val;
});
app.use(function(req, res){
res.json({ name: 'tobi', _id: 12345 });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"name":"tobi"}', done)
})
})
describe('"json spaces" setting', function(){
it('should be undefined by default', function(){
var app = express();
assert(undefined === app.get('json spaces'));
})
it('should be passed to JSON.stringify()', function(done){
var app = express();
app.set('json spaces', 2);
app.use(function(req, res){
res.json({ name: 'tobi', age: 2 });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{\n "name": "tobi",\n "age": 2\n}', done)
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.format.js | test/res.format.js | 'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
var app1 = express();
app1.use(function(req, res, next){
res.format({
'text/plain': function(){
res.send('hey');
},
'text/html': function(){
res.send('<p>hey</p>');
},
'application/json': function(a, b, c){
assert(req === a)
assert(res === b)
assert(next === c)
res.send({ message: 'hey' });
}
});
});
app1.use(function(err, req, res, next){
if (!err.types) throw err;
res.status(err.status)
res.send('Supports: ' + err.types.join(', '))
})
var app2 = express();
app2.use(function(req, res, next){
res.format({
text: function(){ res.send('hey') },
html: function(){ res.send('<p>hey</p>') },
json: function(){ res.send({ message: 'hey' }) }
});
});
app2.use(function(err, req, res, next){
res.status(err.status)
res.send('Supports: ' + err.types.join(', '))
})
var app3 = express();
app3.use(function(req, res, next){
res.format({
text: function(){ res.send('hey') },
default: function (a, b, c) {
assert(req === a)
assert(res === b)
assert(next === c)
res.send('default')
}
})
});
var app4 = express();
app4.get('/', function (req, res) {
res.format({
text: function(){ res.send('hey') },
html: function(){ res.send('<p>hey</p>') },
json: function(){ res.send({ message: 'hey' }) }
});
});
app4.use(function(err, req, res, next){
res.status(err.status)
res.send('Supports: ' + err.types.join(', '))
})
var app5 = express();
app5.use(function (req, res, next) {
res.format({
default: function () { res.send('hey') }
});
});
describe('res', function(){
describe('.format(obj)', function(){
describe('with canonicalized mime types', function(){
test(app1);
})
describe('with extnames', function(){
test(app2);
})
describe('with parameters', function(){
var app = express();
app.use(function(req, res, next){
res.format({
'text/plain; charset=utf-8': function(){ res.send('hey') },
'text/html; foo=bar; bar=baz': function(){ res.send('<p>hey</p>') },
'application/json; q=0.5': function(){ res.send({ message: 'hey' }) }
});
});
app.use(function(err, req, res, next){
res.status(err.status)
res.send('Supports: ' + err.types.join(', '))
});
test(app);
})
describe('given .default', function(){
it('should be invoked instead of auto-responding', function(done){
request(app3)
.get('/')
.set('Accept', 'text/html')
.expect('default', done);
})
it('should work when only .default is provided', function (done) {
request(app5)
.get('/')
.set('Accept', '*/*')
.expect('hey', done);
})
it('should be able to invoke other formatter', function (done) {
var app = express()
app.use(function (req, res, next) {
res.format({
json: function () { res.send('json') },
default: function () {
res.header('x-default', '1')
this.json()
}
})
})
request(app)
.get('/')
.set('Accept', 'text/plain')
.expect(200)
.expect('x-default', '1')
.expect('json')
.end(done)
})
})
describe('in router', function(){
test(app4);
})
describe('in router', function(){
var app = express();
var router = express.Router();
router.get('/', function (req, res) {
res.format({
text: function(){ res.send('hey') },
html: function(){ res.send('<p>hey</p>') },
json: function(){ res.send({ message: 'hey' }) }
});
});
router.use(function(err, req, res, next){
res.status(err.status)
res.send('Supports: ' + err.types.join(', '))
})
app.use(router)
test(app)
})
})
})
function test(app) {
it('should utilize qvalues in negotiation', function(done){
request(app)
.get('/')
.set('Accept', 'text/html; q=.5, application/json, */*; q=.1')
.expect({"message":"hey"}, done);
})
it('should allow wildcard type/subtypes', function(done){
request(app)
.get('/')
.set('Accept', 'text/html; q=.5, application/*, */*; q=.1')
.expect({"message":"hey"}, done);
})
it('should default the Content-Type', function(done){
request(app)
.get('/')
.set('Accept', 'text/html; q=.5, text/plain')
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect('hey', done);
})
it('should set the correct charset for the Content-Type', function (done) {
var cb = after(3, done)
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', 'text/html; charset=utf-8', cb)
request(app)
.get('/')
.set('Accept', 'text/plain')
.expect('Content-Type', 'text/plain; charset=utf-8', cb)
request(app)
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', 'application/json; charset=utf-8', cb)
})
it('should Vary: Accept', function(done){
request(app)
.get('/')
.set('Accept', 'text/html; q=.5, text/plain')
.expect('Vary', 'Accept', done);
})
describe('when Accept is not present', function(){
it('should invoke the first callback', function(done){
request(app)
.get('/')
.expect('hey', done);
})
})
describe('when no match is made', function(){
it('should respond with 406 not acceptable', function(done){
request(app)
.get('/')
.set('Accept', 'foo/bar')
.expect('Supports: text/plain, text/html, application/json')
.expect(406, done)
})
})
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.status.js | test/res.status.js | 'use strict'
const express = require('../.');
const request = require('supertest');
describe('res', function () {
describe('.status(code)', function () {
it('should set the status code when valid', function (done) {
var app = express();
app.use(function (req, res) {
res.status(200).end();
});
request(app)
.get('/')
.expect(200, done);
});
describe('accept valid ranges', function() {
// not testing w/ 100, because that has specific meaning and behavior in Node as Expect: 100-continue
it('should set the response status code to 101', function (done) {
var app = express()
app.use(function (req, res) {
res.status(101).end()
})
request(app)
.get('/')
.expect(101, done)
})
it('should set the response status code to 201', function (done) {
var app = express()
app.use(function (req, res) {
res.status(201).end()
})
request(app)
.get('/')
.expect(201, done)
})
it('should set the response status code to 302', function (done) {
var app = express()
app.use(function (req, res) {
res.status(302).end()
})
request(app)
.get('/')
.expect(302, done)
})
it('should set the response status code to 403', function (done) {
var app = express()
app.use(function (req, res) {
res.status(403).end()
})
request(app)
.get('/')
.expect(403, done)
})
it('should set the response status code to 501', function (done) {
var app = express()
app.use(function (req, res) {
res.status(501).end()
})
request(app)
.get('/')
.expect(501, done)
})
it('should set the response status code to 700', function (done) {
var app = express()
app.use(function (req, res) {
res.status(700).end()
})
request(app)
.get('/')
.expect(700, done)
})
it('should set the response status code to 800', function (done) {
var app = express()
app.use(function (req, res) {
res.status(800).end()
})
request(app)
.get('/')
.expect(800, done)
})
it('should set the response status code to 900', function (done) {
var app = express()
app.use(function (req, res) {
res.status(900).end()
})
request(app)
.get('/')
.expect(900, done)
})
})
describe('invalid status codes', function () {
it('should raise error for status code below 100', function (done) {
var app = express();
app.use(function (req, res) {
res.status(99).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for status code above 999', function (done) {
var app = express();
app.use(function (req, res) {
res.status(1000).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for non-integer status codes', function (done) {
var app = express();
app.use(function (req, res) {
res.status(200.1).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for undefined status code', function (done) {
var app = express();
app.use(function (req, res) {
res.status(undefined).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for null status code', function (done) {
var app = express();
app.use(function (req, res) {
res.status(null).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for string status code', function (done) {
var app = express();
app.use(function (req, res) {
res.status("200").end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
it('should raise error for NaN status code', function (done) {
var app = express();
app.use(function (req, res) {
res.status(NaN).end();
});
request(app)
.get('/')
.expect(500, /Invalid status code/, done);
});
});
});
});
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.accepts.js | test/req.accepts.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.accepts(type)', function(){
it('should return true when Accept is not present', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts('json') ? 'yes' : 'no');
});
request(app)
.get('/')
.expect('yes', done);
})
it('should return true when present', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts('json') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept', 'application/json')
.expect('yes', done);
})
it('should return false otherwise', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts('json') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('no', done);
})
})
it('should accept an argument list of type names', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts('json', 'html'));
});
request(app)
.get('/')
.set('Accept', 'application/json')
.expect('json', done);
})
describe('.accepts(types)', function(){
it('should return the first when Accept is not present', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts(['json', 'html']));
});
request(app)
.get('/')
.expect('json', done);
})
it('should return the first acceptable type', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts(['json', 'html']));
});
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('html', done);
})
it('should return false when no match is made', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts(['text/html', 'application/json']) ? 'yup' : 'nope');
});
request(app)
.get('/')
.set('Accept', 'foo/bar, bar/baz')
.expect('nope', done);
})
it('should take quality into account', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts(['text/html', 'application/json']));
});
request(app)
.get('/')
.set('Accept', '*/html; q=.5, application/json')
.expect('application/json', done);
})
it('should return the first acceptable type with canonical mime types', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts(['application/json', 'text/html']));
});
request(app)
.get('/')
.set('Accept', '*/html')
.expect('text/html', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/app.options.js | test/app.options.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('OPTIONS', function(){
it('should default to the routes defined', function(done){
var app = express();
app.post('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
request(app)
.options('/users')
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should only include each method once', function(done){
var app = express();
app.delete('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
app.get('/users', function(req, res){});
request(app)
.options('/users')
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should not be affected by app.all', function(done){
var app = express();
app.get('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
app.all('/users', function(req, res, next){
res.setHeader('x-hit', '1');
next();
});
request(app)
.options('/users')
.expect('x-hit', '1')
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should not respond if the path is not defined', function(done){
var app = express();
app.get('/users', function(req, res){});
request(app)
.options('/other')
.expect(404, done);
})
it('should forward requests down the middleware chain', function(done){
var app = express();
var router = new express.Router();
router.get('/users', function(req, res){});
app.use(router);
app.get('/other', function(req, res){});
request(app)
.options('/other')
.expect('Allow', 'GET, HEAD')
.expect(200, 'GET, HEAD', done);
})
describe('when error occurs in response handler', function () {
it('should pass error to callback', function (done) {
var app = express();
var router = express.Router();
router.get('/users', function(req, res){});
app.use(function (req, res, next) {
res.writeHead(200);
next();
});
app.use(router);
app.use(function (err, req, res, next) {
res.end('true');
});
request(app)
.options('/users')
.expect(200, 'true', done)
})
})
})
describe('app.options()', function(){
it('should override the default behavior', function(done){
var app = express();
app.options('/users', function(req, res){
res.set('Allow', 'GET');
res.send('GET');
});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
request(app)
.options('/users')
.expect('GET')
.expect('Allow', 'GET', done);
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.xhr.js | test/req.xhr.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.xhr', function(){
before(function () {
this.app = express()
this.app.get('/', function (req, res) {
res.send(req.xhr)
})
})
it('should return true when X-Requested-With is xmlhttprequest', function(done){
request(this.app)
.get('/')
.set('X-Requested-With', 'xmlhttprequest')
.expect(200, 'true', done)
})
it('should case-insensitive', function(done){
request(this.app)
.get('/')
.set('X-Requested-With', 'XMLHttpRequest')
.expect(200, 'true', done)
})
it('should return false otherwise', function(done){
request(this.app)
.get('/')
.set('X-Requested-With', 'blahblah')
.expect(200, 'false', done)
})
it('should return false when not present', function(done){
request(this.app)
.get('/')
.expect(200, 'false', done)
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/express.json.js | test/express.json.js | 'use strict'
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
const { Buffer } = require('node:buffer');
var express = require('..')
var request = require('supertest')
describe('express.json()', function () {
it('should parse JSON', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should handle Content-Length: 0', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.set('Content-Length', '0')
.expect(200, '{}', done)
})
it('should handle empty message-body', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.set('Transfer-Encoding', 'chunked')
.expect(200, '{}', done)
})
it('should handle no message-body', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.unset('Transfer-Encoding')
.expect(200, '{}', done)
})
// The old node error message modification in body parser is catching this
it('should 400 when only whitespace', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.send(' \n')
.expect(400, '[entity.parse.failed] ' + parseError(' \n'), done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.json())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"str":')
.expect(400, /content length/, done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.json())
app.use(express.json())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
describe('when JSON is invalid', function () {
before(function () {
this.app = createApp()
})
it('should 400 for bad token', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{:')
.expect(400, '[entity.parse.failed] ' + parseError('{:'), done)
})
it('should 400 for incomplete', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user"')
.expect(400, '[entity.parse.failed] ' + parseError('{"user"'), done)
})
it('should include original body on error object', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Error-Property', 'body')
.send(' {"user"')
.expect(400, ' {"user"', done)
})
})
describe('with limit option', function () {
it('should 413 when over limit with Content-Length', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/json')
.set('Content-Length', '1034')
.send(JSON.stringify({ str: buf.toString() }))
.expect(413, '[entity.too.large] request entity too large', done)
})
it('should 413 when over limit with chunked encoding', function (done) {
var app = createApp({ limit: '1kb' })
var buf = Buffer.alloc(1024, '.')
var test = request(app).post('/')
test.set('Content-Type', 'application/json')
test.set('Transfer-Encoding', 'chunked')
test.write('{"str":')
test.write('"' + buf.toString() + '"}')
test.expect(413, done)
})
it('should 413 when inflated body over limit', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a040000', 'hex'))
test.expect(413, done)
})
it('should accept number of bytes', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: 1024 }))
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ str: buf.toString() }))
.expect(413, done)
})
it('should not change when options altered', function (done) {
var buf = Buffer.alloc(1024, '.')
var options = { limit: '1kb' }
var app = createApp(options)
options.limit = '100kb'
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ str: buf.toString() }))
.expect(413, done)
})
it('should not hang response', function (done) {
var buf = Buffer.alloc(10240, '.')
var app = createApp({ limit: '8kb' })
var test = request(app).post('/')
test.set('Content-Type', 'application/json')
test.write(buf)
test.write(buf)
test.write(buf)
test.expect(413, done)
})
it('should not error when inflating', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a0400', 'hex'))
test.expect(413, done)
})
})
describe('with inflate option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ inflate: false })
})
it('should not accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(415, '[encoding.unsupported] content encoding unsupported', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ inflate: true })
})
it('should accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
})
})
describe('with strict option', function () {
describe('when undefined', function () {
before(function () {
this.app = createApp()
})
it('should 400 on primitives', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('true')
.expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done)
})
})
describe('when false', function () {
before(function () {
this.app = createApp({ strict: false })
})
it('should parse primitives', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('true')
.expect(200, 'true', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ strict: true })
})
it('should not parse primitives', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('true')
.expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done)
})
it('should not parse primitives with leading whitespaces', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send(' true')
.expect(400, '[entity.parse.failed] ' + parseError(' #rue').replace(/#/g, 't'), done)
})
it('should allow leading whitespaces in JSON', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send(' { "user": "tobi" }')
.expect(200, '{"user":"tobi"}', done)
})
it('should include correct message in stack trace', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Error-Property', 'stack')
.send('true')
.expect(400)
.expect(shouldContainInBody(parseError('#rue').replace(/#/g, 't')))
.end(done)
})
})
})
describe('with type option', function () {
describe('when "application/vnd.api+json"', function () {
before(function () {
this.app = createApp({ type: 'application/vnd.api+json' })
})
it('should parse JSON for custom type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/vnd.api+json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore standard type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '', done)
})
})
describe('when ["application/json", "application/vnd.api+json"]', function () {
before(function () {
this.app = createApp({
type: ['application/json', 'application/vnd.api+json']
})
})
it('should parse JSON for "application/json"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should parse JSON for "application/vnd.api+json"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/vnd.api+json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore "application/x-json"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-json')
.send('{"user":"tobi"}')
.expect(200, '', done)
})
})
describe('when a function', function () {
it('should parse when truthy value returned', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return req.headers['content-type'] === 'application/vnd.api+json'
}
request(app)
.post('/')
.set('Content-Type', 'application/vnd.api+json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should work without content-type', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return true
}
var test = request(app).post('/')
test.write('{"user":"tobi"}')
test.expect(200, '{"user":"tobi"}', done)
})
it('should not invoke without a body', function (done) {
var app = createApp({ type: accept })
function accept (req) {
throw new Error('oops!')
}
request(app)
.get('/')
.expect(404, done)
})
})
})
describe('with verify option', function () {
it('should assert value if function', function () {
assert.throws(createApp.bind(null, { verify: 'lol' }),
/TypeError: option verify must be function/)
})
it('should error from verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('["tobi"]')
.expect(403, '[entity.verify.failed] no arrays', done)
})
it('should allow custom codes', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x5b) return
var err = new Error('no arrays')
err.status = 400
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('["tobi"]')
.expect(400, '[entity.verify.failed] no arrays', done)
})
it('should allow custom type', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x5b) return
var err = new Error('no arrays')
err.type = 'foo.bar'
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('["tobi"]')
.expect(403, '[foo.bar] no arrays', done)
})
it('should include original body on error object', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Error-Property', 'body')
.send('["tobi"]')
.expect(403, '["tobi"]', done)
})
it('should allow pass-through', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200, '{"user":"tobi"}', done)
})
it('should work with different charsets', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/json; charset=utf-16')
test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should 415 on unknown charset prior to verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
throw new Error('unexpected verify call')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/json; charset=x-bogus')
test.write(Buffer.from('00000000', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)
})
})
describe('async local storage', function () {
before(function () {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(express.json())
app.use(function (req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
next()
})
app.use(function (err, req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.status(err.status || 500)
res.send('[' + err.type + '] ' + err.message)
})
app.post('/', function (req, res) {
res.json(req.body)
})
this.app = app
})
it('should persist store', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"tobi"}')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('{"user":"tobi"}')
.end(done)
})
it('should persist store when unmatched content-type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/fizzbuzz')
.send('buzz')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('')
.end(done)
})
it('should persist store when inflated', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(200)
test.expect('x-store-foo', 'bar')
test.expect('{"name":"论"}')
test.end(done)
})
it('should persist store when inflate error', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(400)
test.expect('x-store-foo', 'bar')
test.end(done)
})
it('should persist store when parse error', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":')
.expect(400)
.expect('x-store-foo', 'bar')
.end(done)
})
it('should persist store when limit exceeded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/json')
.send('{"user":"' + Buffer.alloc(1024 * 100, '.').toString() + '"}')
.expect(413)
.expect('x-store-foo', 'bar')
.end(done)
})
})
describe('charset', function () {
before(function () {
this.app = createApp()
})
it('should parse utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json; charset=utf-8')
test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should parse utf-16', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json; charset=utf-16')
test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should parse when content-length != char length', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json; charset=utf-8')
test.set('Content-Length', '13')
test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex'))
test.expect(200, '{"test":"å"}', done)
})
it('should default to utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should fail on unknown charset', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json; charset=koi8-r')
test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done)
})
})
describe('encoding', function () {
before(function () {
this.app = createApp({ limit: '1kb' })
})
it('should parse without encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support identity encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'identity')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support gzip encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support deflate encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'deflate')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should be case-insensitive', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'GZIP')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should 415 on unknown encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'nulls')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('000000000000', 'hex'))
test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)
})
it('should 400 on malformed encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))
test.expect(400, done)
})
it('should 413 when inflated value exceeds limit', function (done) {
// gzip'd data exceeds 1kb, but deflated below 1kb
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/json')
test.write(Buffer.from('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex'))
test.write(Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex'))
test.write(Buffer.from('0000000000000000004f0625b3b71650c30000', 'hex'))
test.expect(413, done)
})
})
})
function createApp (options) {
var app = express()
app.use(express.json(options))
app.use(function (err, req, res, next) {
// console.log(err)
res.status(err.status || 500)
res.send(String(req.headers['x-error-property']
? err[req.headers['x-error-property']]
: ('[' + err.type + '] ' + err.message)))
})
app.post('/', function (req, res) {
res.json(req.body)
})
return app
}
function parseError (str) {
try {
JSON.parse(str); throw new SyntaxError('strict violation')
} catch (e) {
return e.message
}
}
function shouldContainInBody (str) {
return function (res) {
assert.ok(res.text.indexOf(str) !== -1,
'expected \'' + res.text + '\' to contain \'' + str + '\'')
}
}
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/req.acceptsLanguages.js | test/req.acceptsLanguages.js | 'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.acceptsLanguages', function(){
it('should return language if accepted', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send({
'en-us': req.acceptsLanguages('en-us'),
en: req.acceptsLanguages('en')
})
})
request(app)
.get('/')
.set('Accept-Language', 'en;q=.5, en-us')
.expect(200, { 'en-us': 'en-us', en: 'en' }, done)
})
it('should be false if language not accepted', function(done){
var app = express();
app.get('/', function (req, res) {
res.send({
es: req.acceptsLanguages('es')
})
})
request(app)
.get('/')
.set('Accept-Language', 'en;q=.5, en-us')
.expect(200, { es: false }, done)
})
describe('when Accept-Language is not present', function(){
it('should always return language', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send({
en: req.acceptsLanguages('en'),
es: req.acceptsLanguages('es'),
jp: req.acceptsLanguages('jp')
})
})
request(app)
.get('/')
.expect(200, { en: 'en', es: 'es', jp: 'jp' }, done)
})
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
expressjs/express | https://github.com/expressjs/express/blob/c2fb76e99f7379b706a5510b4b2dd08a1b710b7b/test/res.set.js | test/res.set.js | 'use strict'
var express = require('..');
var request = require('supertest');
describe('res', function(){
describe('.set(field, value)', function(){
it('should set the response header field', function(done){
var app = express();
app.use(function(req, res){
res.set('Content-Type', 'text/x-foo; charset=utf-8').end();
});
request(app)
.get('/')
.expect('Content-Type', 'text/x-foo; charset=utf-8')
.end(done);
})
it('should coerce to a string', function (done) {
var app = express();
app.use(function (req, res) {
res.set('X-Number', 123);
res.end(typeof res.get('X-Number'));
});
request(app)
.get('/')
.expect('X-Number', '123')
.expect(200, 'string', done);
})
})
describe('.set(field, values)', function(){
it('should set multiple response header fields', function(done){
var app = express();
app.use(function(req, res){
res.set('Set-Cookie', ["type=ninja", "language=javascript"]);
res.send(res.get('Set-Cookie'));
});
request(app)
.get('/')
.expect('["type=ninja","language=javascript"]', done);
})
it('should coerce to an array of strings', function (done) {
var app = express();
app.use(function (req, res) {
res.set('X-Numbers', [123, 456]);
res.end(JSON.stringify(res.get('X-Numbers')));
});
request(app)
.get('/')
.expect('X-Numbers', '123, 456')
.expect(200, '["123","456"]', done);
})
it('should not set a charset of one is already set', function (done) {
var app = express();
app.use(function (req, res) {
res.set('Content-Type', 'text/html; charset=lol');
res.end();
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=lol')
.expect(200, done);
})
it('should throw when Content-Type is an array', function (done) {
var app = express()
app.use(function (req, res) {
res.set('Content-Type', ['text/html'])
res.end()
});
request(app)
.get('/')
.expect(500, /TypeError: Content-Type cannot be set to an Array/, done)
})
})
describe('.set(object)', function(){
it('should set multiple fields', function(done){
var app = express();
app.use(function(req, res){
res.set({
'X-Foo': 'bar',
'X-Bar': 'baz'
}).end();
});
request(app)
.get('/')
.expect('X-Foo', 'bar')
.expect('X-Bar', 'baz')
.end(done);
})
it('should coerce to a string', function (done) {
var app = express();
app.use(function (req, res) {
res.set({ 'X-Number': 123 });
res.end(typeof res.get('X-Number'));
});
request(app)
.get('/')
.expect('X-Number', '123')
.expect(200, 'string', done);
})
})
})
| javascript | MIT | c2fb76e99f7379b706a5510b4b2dd08a1b710b7b | 2026-01-04T14:56:49.655129Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.