Next.js has integrated support for Jest.

This also uncovered that we were ignoring the user's country and
thus defaulting to the US in the Next.js port, so this also sets
up country code detection for Next.js.

This ports a couple of the existing tests; more complex ones will
be ported in followup commits.
This commit is contained in:
Vincent 2023-06-26 17:09:08 +02:00 коммит произвёл Vincent
Родитель d849899312
Коммит c9416df615
11 изменённых файлов: 5844 добавлений и 4946 удалений

210
jest.config.cjs Normal file
Просмотреть файл

@ -0,0 +1,210 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nextJest = require("next/jest");
const createJestConfig = nextJest({ dir: "./" })
// See https://nextjs.org/docs/architecture/nextjs-compiler#jest
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
/** @type {import("@jest/types").Config.InitialOptions} */
const customJestConfig = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
modulePathIgnorePatterns: ["e2e/", "index.test.js", "email.test.js", "settings.test.js", "breachResolution.test.js"],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "jsdom",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
const jestConfig = createJestConfig(customJestConfig);
module.exports = jestConfig;

10271
package-lock.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -13,7 +13,7 @@
"start": "next start",
"lint": "stylelint '**/*.scss' && prettier --check './src' && next lint --max-warnings=0",
"fix": "prettier --write './src' && next lint --fix && stylelint --fix '**/*.scss'",
"test": "NODE_OPTIONS=--loader=testdouble c8 ava",
"test": "jest",
"e2e": "playwright test src/e2e/",
"functions": "nodemon --exec 'functions-framework --target=app --signature-type=http --source=src/cloud-functions'",
"db:migrate": "node -r dotenv/config node_modules/knex/bin/cli.js migrate:latest --knexfile src/db/knexfile.js",
@ -33,11 +33,6 @@
},
"ext": "js,css,json,ftl,env"
},
"ava": {
"files": [
"!src/e2e/"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/mozilla/blurts-server.git"
@ -99,7 +94,6 @@
"@types/uuid": "^9.0.1",
"@typescript-eslint/eslint-plugin": "^5.59.1",
"@typescript-eslint/parser": "^5.59.1",
"ava": "^5.1.0",
"c8": "^7.12.0",
"eslint": "^8.40.0",
"eslint-import-resolver-typescript": "^3.5.5",
@ -109,6 +103,8 @@
"eslint-plugin-jsdoc": "^40.0.0",
"eslint-plugin-storybook": "^0.6.12",
"husky": "^8.0.3",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"lint-staged": "^13.2.2",
"node-mocks-http": "^1.12.1",
"nodemon": "^2.0.20",
@ -118,7 +114,7 @@
"stylelint": "^15.6.0",
"stylelint-config-recommended-scss": "^11.0.0",
"stylelint-scss": "^5.0.0",
"testdouble": "^3.16.8",
"ts-jest": "^29.1.0",
"typescript": "^5.0.4"
}
}

Просмотреть файл

@ -5,6 +5,7 @@
import Image from "next/image";
import Script from "next/script";
import { getServerSession } from "next-auth";
import { headers } from "next/headers";
import { CircleChartProps, UserBreaches } from "./breaches.d";
import AppConstants from "../../../../../appConstants.js";
@ -17,6 +18,7 @@ import ImageIconEmail from "../../../../../client/images/icon-email.svg";
import { BreachesTable } from "../../../components/server/BreachesTable";
import { getComponentAsString } from "../../../functions/server/getComponentAsString";
import { getCountryCode } from "../../../../functions/server/getCountryCode";
export async function generateMetadata() {
const l10n = getL10n();
@ -63,12 +65,16 @@ declare global {
export default async function UserBreaches() {
const session = await getServerSession(authOptions);
const l10n = getL10n();
const headerList = headers();
const userBreachesData: UserBreaches = await getUserBreaches({
// `(authenticated)/layout.tsx` ensures that `session` is not undefined,
// so the type assertion should be safe:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
user: session!.user as any,
options: {
countryCode: getCountryCode(headerList),
},
});
type FxaSubscriptionResponse = {

Просмотреть файл

@ -0,0 +1,78 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { it, expect, jest } from "@jest/globals";
import { getCountryCode } from "./getCountryCode";
import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
/* eslint-disable @typescript-eslint/no-explicit-any */
it("returns the GCP-detected country", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((header: string) => {
if (header === "X-Client-Region") {
return "NL";
}
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("nl");
});
it("returns the single language from the Accept-Language if no GCP-detected country is available", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((header: string) => {
if (header === "Accept-Language") {
return "nl-NL";
}
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("nl");
});
it("returns the first language from the Accept-Language if no GCP-detected country is available", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((header: string) => {
if (header === "Accept-Language") {
return "nl-NL, en-US";
}
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("nl");
});
it("returns the first language from the Accept-Language if no GCP-detected country is available, without weights being a problem", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((header: string) => {
if (header === "Accept-Language") {
return "nl-NL;q=0.8, en-US";
}
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("nl");
});
it("returns the first language from the Accept-Language if no GCP-detected country is available, ignoring locales without a country code", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((header: string) => {
if (header === "Accept-Language") {
return "nl;q=0.8, en-US";
}
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("us");
});
it("defaults to US", () => {
const headers: Partial<jest.Mocked<ReadonlyHeaders>> = {
get: jest.fn((_header: string) => {
return null;
}),
};
expect(getCountryCode(headers as any)).toBe("us");
});

Просмотреть файл

@ -0,0 +1,30 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import type { headers as headersGetter } from "next/headers";
export function getCountryCode(
headers: ReturnType<typeof headersGetter>
): string {
// GCP can detect the user's country from their IP addresses, and pass it to
// us through this header:
const gcpDetectedRegion = headers.get("X-Client-Region");
if (gcpDetectedRegion) {
return gcpDetectedRegion.toLowerCase();
}
// On stage and production, the `X-Client-Region` should be available. To be
// able to locally test country-specific behaviour, we fall back to the
// Accept-Language:
const acceptLanguage = headers.get("Accept-Language");
if (acceptLanguage) {
const acceptedLocales = acceptLanguage.split(",");
const primaryLocale = acceptedLocales[0] ?? "";
const [locale, _weight] = primaryLocale.split(";");
const [_language, country] = (locale ?? "").split("-");
if (country) {
return country.toLowerCase();
}
}
return "us";
}

Просмотреть файл

@ -12,13 +12,15 @@ import { getAllEmailsAndBreaches } from "../../../../src/utils/breaches.js";
export async function getUserBreaches({
user,
options = {},
}: {
user: Session["user"] & { email: string };
options?: Parameters<typeof appendBreachResolutionChecklist>[1];
}) {
const subscriber = await getSubscriberByEmail(user.email);
const allBreaches = await getBreaches();
const breachesData = await getAllEmailsAndBreaches(subscriber, allBreaches);
appendBreachResolutionChecklist(breachesData);
appendBreachResolutionChecklist(breachesData, options);
const emailVerifiedCount = breachesData.verifiedEmails?.length ?? 0;
const emailTotalCount =

Просмотреть файл

@ -2,23 +2,23 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import test from 'ava'
import { test, expect } from "@jest/globals";
import { breachedDataTypes, breachSummary } from './breachSummary.js'
test('breachSummary: handles null input', t => {
test('breachSummary: handles null input', () => {
const verifiedEmails = null
const resp = breachSummary(verifiedEmails)
t.is(resp.monitoredEmails.count, 0)
expect(resp.monitoredEmails.count).toBe(0);
})
test('breachSummary: handles empty input', t => {
test('breachSummary: handles empty input', () => {
const verifiedEmails = []
const resp = breachSummary(verifiedEmails)
t.is(resp.monitoredEmails.count, 0)
expect(resp.monitoredEmails.count).toBe(0);
})
test('breachSummary: unresolved breaches', t => {
test('breachSummary: unresolved breaches', () => {
const verifiedEmails = [{
email: 'test@test.com',
breaches: [],
@ -51,12 +51,12 @@ test('breachSummary: unresolved breaches', t => {
primary: false
}]
const resp = breachSummary(verifiedEmails)
t.is(resp.monitoredEmails.count, 2)
t.is(resp.numBreaches.count, 1)
t.is(resp.numBreaches.numResolved, 0)
t.is(resp.numBreaches.numUnresolved, 1)
expect(resp.monitoredEmails.count).toBe(2)
expect(resp.numBreaches.count).toBe(1)
expect(resp.numBreaches.numResolved).toBe(0)
expect(resp.numBreaches.numUnresolved).toBe(1)
})
test('breachSummary: resolved breaches', t => {
test('breachSummary: resolved breaches', () => {
const verifiedEmails = [{
email: 'test@test.com',
breaches: [{
@ -120,13 +120,13 @@ test('breachSummary: resolved breaches', t => {
primary: false
}]
const resp = breachSummary(verifiedEmails)
t.is(resp.monitoredEmails.count, 2)
t.is(resp.numBreaches.count, 4)
t.is(resp.numBreaches.numResolved, 2)
t.is(resp.numBreaches.numUnresolved, 2)
expect(resp.monitoredEmails.count).toBe(2)
expect(resp.numBreaches.count).toBe(4)
expect(resp.numBreaches.numResolved).toBe(2)
expect(resp.numBreaches.numUnresolved).toBe(2)
})
test('breachedDataTypes', t => {
test('breachedDataTypes', () => {
const verifiedEmails = [{
email: 'test@test.com',
breaches: [{
@ -190,8 +190,8 @@ test('breachedDataTypes', t => {
primary: false
}]
const resp = breachedDataTypes(verifiedEmails, 'test2@test.com')
t.is(resp['test@test.com']?.passwords, 1)
t.is(resp['test@test.com']['email-addresses'], 1)
t.is(resp['test2@test.com']?.passwords, 1)
t.is(resp['test2@test.com']['email-addresses'], 2)
expect(resp['test@test.com']?.passwords).toBe(1);
expect(resp['test@test.com']['email-addresses']).toBe(1);
expect(resp['test2@test.com']?.passwords).toBe(1);
expect(resp['test2@test.com']['email-addresses']).toBe(2);
})

Просмотреть файл

@ -1,61 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import test from 'ava'
import { getCountryCode } from './countryCode.js'
test('getCountryCode: GCP-detected country', t => {
const getHeader = (header) => {
if (header === 'X-Client-Region') {
return 'NL'
}
return undefined
}
t.is(getCountryCode({ get: getHeader }), 'nl')
})
test('getCountryCode: Accept-Language with a single locale', t => {
const getHeader = (header) => {
if (header === 'Accept-Language') {
return 'nl-NL'
}
return undefined
}
t.is(getCountryCode({ get: getHeader }), 'nl')
})
test('getCountryCode: Accept-Language with multiple locales', t => {
const getHeader = (header) => {
if (header === 'Accept-Language') {
return 'nl-NL, en-US'
}
return undefined
}
t.is(getCountryCode({ get: getHeader }), 'nl')
})
test('getCountryCode: Accept-Language with multiple locales, with weightings', t => {
const getHeader = (header) => {
if (header === 'Accept-Language') {
return 'nl-NL;q=0.8, en-US'
}
return undefined
}
t.is(getCountryCode({ get: getHeader }), 'nl')
})
test('getCountryCode: Accept-Language with a language without a country code', t => {
const getHeader = (header) => {
if (header === 'Accept-Language') {
return 'nl;q=0.8, en-US'
}
return undefined
}
t.is(getCountryCode({ get: getHeader }), 'us')
})
test('getCountryCode: defaults to US', t => {
t.is(getCountryCode({ get: () => undefined }), 'us')
})

Просмотреть файл

@ -2,7 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import test from 'ava'
import { test, expect } from "@jest/globals";
import {
BadRequestError,
UnauthorizedError,
@ -13,51 +13,51 @@ import {
InternalServerError
} from './error.js'
test('BadRequestError', t => {
test('BadRequestError', () => {
const errorMessage = 'BadRequestError message'
const error = new BadRequestError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Bad Request')
})
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Bad Request");
});
test('UnauthorizedError', t => {
test('UnauthorizedError', () => {
const errorMessage = 'UnauthorizedError message'
const error = new UnauthorizedError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Unauthorized')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Unauthorized");
})
test('ForbiddenError', t => {
test('ForbiddenError', () => {
const errorMessage = 'ForbiddenError message'
const error = new ForbiddenError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Forbidden')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Forbidden");
})
test('MethodNotAllowedError', t => {
test('MethodNotAllowedError', () => {
const errorMessage = 'MethodNotAllowedError message'
const error = new MethodNotAllowedError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Method Not Allowed')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Method Not Allowed");
})
test('ConflictError', t => {
test('ConflictError', () => {
const errorMessage = 'ConflictError message'
const error = new ConflictError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Conflict')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Conflict");
})
test('TooManyRequestsError', t => {
test('TooManyRequestsError', () => {
const errorMessage = 'TooManyRequestsError message'
const error = new TooManyRequestsError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Too Many Requests')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Too Many Requests");
})
test('InternalServerError', t => {
test('InternalServerError', () => {
const errorMessage = 'InternalServerError message'
const error = new InternalServerError(errorMessage)
t.is(error.message, errorMessage)
t.is(error.name, 'Internal Server Error')
expect(error.message).toBe(errorMessage);
expect(error.name).toBe("Internal Server Error");
})

Просмотреть файл

@ -1,32 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import test from 'ava'
import { initFluentBundles, updateLocale, getMessage, getRawMessage } from './fluent.js'
test.before(async () => {
await initFluentBundles()
updateLocale('en')
})
test('getMessage', t => {
const resp = getMessage('home-not-found')
t.is(resp, 'Page not found.')
})
test('getMessage: id cannot be found', t => {
const resp = getMessage('invalid id')
t.is(resp, 'invalid id')
})
test('getRawMessage', t => {
const resp = getRawMessage('home-not-found')
t.is(resp, 'Page not found.')
})
test('getRawMessage: id cannot be found', t => {
const resp = getRawMessage('invalid id')
t.is(resp, 'invalid id')
})