jest.config.ts 10 KB

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