jest.config.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import type {Config} from '@jest/types';
  2. import path from 'node:path';
  3. import process from 'node:process';
  4. import babelConfig from './babel.config';
  5. const {
  6. CI,
  7. JEST_TESTS,
  8. JEST_TEST_BALANCER,
  9. CI_NODE_TOTAL,
  10. CI_NODE_INDEX,
  11. GITHUB_PR_SHA,
  12. GITHUB_PR_REF,
  13. GITHUB_RUN_ID,
  14. GITHUB_RUN_ATTEMPT,
  15. } = process.env;
  16. const IS_MASTER_BRANCH = GITHUB_PR_REF === 'refs/heads/master';
  17. const BALANCE_RESULTS_PATH = path.resolve(
  18. __dirname,
  19. 'tests',
  20. 'js',
  21. 'test-balancer',
  22. 'jest-balance.json'
  23. );
  24. const optionalTags: {
  25. balancer?: boolean;
  26. balancer_strategy?: string;
  27. } = {
  28. balancer: false,
  29. };
  30. if (!!JEST_TEST_BALANCER && !CI) {
  31. throw new Error(
  32. '[Operation only allowed in CI]: Jest test balancer should never be ran manually as you risk skewing the numbers - please trigger the automated github workflow at https://github.com/getsentry/sentry/actions/workflows/jest-balance.yml'
  33. );
  34. }
  35. /**
  36. * In CI we may need to shard our jest tests so that we can parellize the test runs
  37. *
  38. * `JEST_TESTS` is a list of all tests that will run, captured by `jest --listTests`
  39. * Then we split up the tests based on the total number of CI instances that will
  40. * be running the tests.
  41. */
  42. let testMatch: string[] | undefined;
  43. function getTestsForGroup(
  44. nodeIndex: number,
  45. nodeTotal: number,
  46. allTests: ReadonlyArray<string>,
  47. testStats: Record<string, number>
  48. ): string[] {
  49. const speculatedSuiteDuration = Object.values(testStats).reduce((a, b) => a + b, 0);
  50. const targetDuration = speculatedSuiteDuration / nodeTotal;
  51. if (speculatedSuiteDuration <= 0) {
  52. throw new Error('Speculated suite duration is <= 0');
  53. }
  54. // We are going to take all of our tests and split them into groups.
  55. // If we have a test without a known duration, we will default it to 2 second
  56. // This is to ensure that we still assign some weight to the tests and still attempt to somewhat balance them.
  57. // The 1.5s default is selected as a p50 value of all of our JS tests in CI (as of 2022-10-26) taken from our sentry performance monitoring.
  58. const tests = new Map<string, number>();
  59. const SUITE_P50_DURATION_MS = 1500;
  60. // First, iterate over all of the tests we have stats for.
  61. for (const test in testStats) {
  62. if (testStats[test] <= 0) {
  63. throw new Error(`Test duration is <= 0 for ${test}`);
  64. }
  65. tests.set(test, testStats[test]);
  66. }
  67. // Then, iterate over all of the remaining tests and assign them a default duration.
  68. for (const test of allTests) {
  69. if (tests.has(test)) {
  70. continue;
  71. }
  72. tests.set(test, SUITE_P50_DURATION_MS);
  73. }
  74. // Sanity check to ensure that we have all of our tests accounted for, we need to fail
  75. // if this is not the case as we risk not executing some tests and passing the build.
  76. if (tests.size < allTests.length) {
  77. throw new Error(
  78. `All tests should be accounted for, missing ${allTests.length - tests.size}`
  79. );
  80. }
  81. const groups: string[][] = [];
  82. // We sort files by path so that we try and improve the transformer cache hit rate.
  83. // Colocated domain specific files are likely to require other domain specific files.
  84. const testsSortedByPath = Array.from(tests.entries()).sort((a, b) => {
  85. return a[0].localeCompare(b[0]);
  86. });
  87. for (let group = 0; group < nodeTotal; group++) {
  88. groups[group] = [];
  89. let duration = 0;
  90. // While we are under our target duration and there are tests in the group
  91. while (duration < targetDuration && testsSortedByPath.length > 0) {
  92. // We peek the next item to check that it is not some super long running
  93. // test that may exceed our target duration. For example, if target runtime for each group is
  94. // 10 seconds, we have currently accounted for 9 seconds, and the next test is 5 seconds, we
  95. // want to move that test to the next group so as to avoid a 40% imbalance.
  96. const peek = testsSortedByPath[testsSortedByPath.length - 1];
  97. if (duration + peek[1] > targetDuration && peek[1] > 30_000) {
  98. break;
  99. }
  100. const nextTest = testsSortedByPath.pop();
  101. if (!nextTest) {
  102. throw new TypeError('Received falsy test' + JSON.stringify(nextTest));
  103. }
  104. groups[group].push(nextTest[0]);
  105. duration += nextTest[1];
  106. }
  107. }
  108. // Whatever may be left over will get round robin'd into the groups.
  109. let i = 0;
  110. while (testsSortedByPath.length) {
  111. const nextTest = testsSortedByPath.pop();
  112. if (!nextTest) {
  113. throw new TypeError('Received falsy test' + JSON.stringify(nextTest));
  114. }
  115. groups[i % 4].push(nextTest[0]);
  116. i++;
  117. }
  118. // Make sure we exhausted all tests before proceeding.
  119. if (testsSortedByPath.length > 0) {
  120. throw new Error('All tests should be accounted for');
  121. }
  122. // We need to ensure that everything from jest --listTests is accounted for.
  123. for (const test of allTests) {
  124. if (!tests.has(test)) {
  125. throw new Error(`Test ${test} is not accounted for`);
  126. }
  127. }
  128. if (!groups[nodeIndex]) {
  129. throw new Error(`No tests found for node ${nodeIndex}`);
  130. }
  131. return groups[nodeIndex].map(test => `<rootDir>/${test}`);
  132. }
  133. if (
  134. JEST_TESTS &&
  135. typeof CI_NODE_TOTAL !== 'undefined' &&
  136. typeof CI_NODE_INDEX !== 'undefined'
  137. ) {
  138. let balance: null | Record<string, number> = null;
  139. try {
  140. balance = require(BALANCE_RESULTS_PATH);
  141. } catch (err) {
  142. // Just ignore if balance results doesn't exist
  143. }
  144. // Taken from https://github.com/facebook/jest/issues/6270#issue-326653779
  145. const envTestList: string[] = JSON.parse(JEST_TESTS).map(file =>
  146. file.replace(__dirname, '')
  147. );
  148. const nodeTotal = Number(CI_NODE_TOTAL);
  149. const nodeIndex = Number(CI_NODE_INDEX);
  150. if (balance) {
  151. optionalTags.balancer = true;
  152. optionalTags.balancer_strategy = 'by_path';
  153. testMatch = getTestsForGroup(nodeIndex, nodeTotal, envTestList, balance);
  154. } else {
  155. const tests = envTestList.sort((a, b) => b.localeCompare(a));
  156. const length = tests.length;
  157. const size = Math.floor(length / nodeTotal);
  158. const remainder = length % nodeTotal;
  159. const offset = Math.min(nodeIndex, remainder) + nodeIndex * size;
  160. const chunk = size + (nodeIndex < remainder ? 1 : 0);
  161. testMatch = tests.slice(offset, offset + chunk).map(test => '<rootDir>' + test);
  162. }
  163. }
  164. /**
  165. * For performance we don't want to try and compile everything in the
  166. * node_modules, but some packages which use ES6 syntax only NEED to be
  167. * transformed.
  168. */
  169. const ESM_NODE_MODULES = ['screenfull'];
  170. const config: Config.InitialOptions = {
  171. verbose: false,
  172. collectCoverageFrom: [
  173. 'static/app/**/*.{js,jsx,ts,tsx}',
  174. '!static/app/**/*.spec.{js,jsx,ts,tsx}',
  175. ],
  176. coverageReporters: ['html', 'cobertura'],
  177. coverageDirectory: '.artifacts/coverage',
  178. moduleNameMapper: {
  179. '^sentry/(.*)': '<rootDir>/static/app/$1',
  180. '^sentry-fixture/(.*)': '<rootDir>/tests/js/fixtures/$1',
  181. '^sentry-test/(.*)': '<rootDir>/tests/js/sentry-test/$1',
  182. '^sentry-locale/(.*)': '<rootDir>/src/sentry/locale/$1',
  183. '\\.(css|less|png|jpg|mp4)$': '<rootDir>/tests/js/sentry-test/importStyleMock.js',
  184. '\\.(svg)$': '<rootDir>/tests/js/sentry-test/svgMock.js',
  185. // Disable echarts in test, since they're very slow and take time to
  186. // transform
  187. '^echarts/(.*)': '<rootDir>/tests/js/sentry-test/echartsMock.js',
  188. '^zrender/(.*)': '<rootDir>/tests/js/sentry-test/echartsMock.js',
  189. },
  190. setupFiles: [
  191. '<rootDir>/static/app/utils/silence-react-unsafe-warnings.ts',
  192. 'jest-canvas-mock',
  193. ],
  194. setupFilesAfterEnv: [
  195. '<rootDir>/tests/js/setup.ts',
  196. '<rootDir>/tests/js/setupFramework.ts',
  197. ],
  198. testMatch: testMatch || ['<rootDir>/(static|tests/js)/**/?(*.)+(spec|test).[jt]s?(x)'],
  199. testPathIgnorePatterns: ['<rootDir>/tests/sentry/lang/javascript/'],
  200. unmockedModulePathPatterns: [
  201. '<rootDir>/node_modules/react',
  202. '<rootDir>/node_modules/reflux',
  203. ],
  204. transform: {
  205. '^.+\\.jsx?$': ['babel-jest', babelConfig as any],
  206. '^.+\\.tsx?$': ['babel-jest', babelConfig as any],
  207. '^.+\\.pegjs?$': '<rootDir>/tests/js/jest-pegjs-transform.js',
  208. },
  209. transformIgnorePatterns: [
  210. ESM_NODE_MODULES.length
  211. ? `/node_modules/(?!${ESM_NODE_MODULES.join('|')})`
  212. : '/node_modules/',
  213. ],
  214. moduleFileExtensions: ['js', 'ts', 'jsx', 'tsx', 'pegjs'],
  215. globals: {},
  216. testResultsProcessor: JEST_TEST_BALANCER
  217. ? '<rootDir>/tests/js/test-balancer/index.js'
  218. : undefined,
  219. reporters: [
  220. 'default',
  221. [
  222. 'jest-junit',
  223. {
  224. outputDirectory: '.artifacts',
  225. outputName: 'jest.junit.xml',
  226. },
  227. ],
  228. ],
  229. /**
  230. * jest.clearAllMocks() automatically called before each test
  231. * @link - https://jestjs.io/docs/configuration#clearmocks-boolean
  232. */
  233. clearMocks: true,
  234. // To disable the sentry jest integration, set this to 'jsdom'
  235. testEnvironment: '@sentry/jest-environment/jsdom',
  236. testEnvironmentOptions: {
  237. sentryConfig: {
  238. init: {
  239. // jest project under Sentry organization (dev productivity team)
  240. dsn: CI
  241. ? 'https://3fe1dce93e3a4267979ebad67f3de327@o1.ingest.us.sentry.io/4857230'
  242. : false,
  243. // Use production env to reduce sampling of commits on master
  244. environment: CI ? (IS_MASTER_BRANCH ? 'ci:master' : 'ci:pull_request') : 'local',
  245. tracesSampleRate: CI ? 0.75 : 0,
  246. profilesSampleRate: 0,
  247. transportOptions: {keepAlive: true},
  248. },
  249. transactionOptions: {
  250. tags: {
  251. ...optionalTags,
  252. branch: GITHUB_PR_REF,
  253. commit: GITHUB_PR_SHA,
  254. github_run_attempt: GITHUB_RUN_ATTEMPT,
  255. github_actions_run: `https://github.com/getsentry/sentry/actions/runs/${GITHUB_RUN_ID}`,
  256. },
  257. },
  258. },
  259. },
  260. };
  261. export default config;