Skip to content

Commit 381c81a

Browse files
committed
fix: setup jest and react testing library
1 parent 509b8a5 commit 381c81a

18 files changed

+1055
-1293
lines changed

.eslintrc.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@ module.exports = {
3434
'simple-import-sort/imports': 'warn',
3535
'simple-import-sort/exports': 'warn',
3636
'react-hooks/exhaustive-deps': 'warn',
37-
'react/react-in-jsx-scope': 'warn',
38-
'@typescript-eslint/no-explicit-any': 'warn',
37+
'react/react-in-jsx-scope': 'off',
38+
'react/jsx-uses-react': 'off',
3939
'react/prop-types': 'off',
40+
'@typescript-eslint/no-explicit-any': 'warn',
4041
'@typescript-eslint/no-var-requires': 'off',
4142
},
4243
overrides: [

__mocks__/fileMock.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = 'test-file-stub';

__mocks__/react-dom-server.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
renderToString: jest.fn(() => '<div>mocked HTML</div>'),
3+
renderToStaticMarkup: jest.fn(() => '<Xml xmlns=`http://www.w3.org/1999/xhtml` id=`toolbox`>mocked XML</Xml>'),
4+
};

__mocks__/styleMock.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = {};

__mocks__/translation.mock.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const Localize = ({ i18n_default_text, values }) => {
2+
// Replace placeholders in the default text with actual values
3+
const localizedText = i18n_default_text.replace(/\{\{(\w+)\}\}/g, (match, key) => values[key] || match);
4+
5+
return localizedText || null;
6+
};
7+
8+
// Mock for useTranslations hook
9+
const useTranslations = () => ({
10+
localize: jest.fn((text, args) => {
11+
return text.replace(/{{(.*?)}}/g, (_, match) => args[match.trim()]);
12+
}),
13+
currentLang: 'EN',
14+
});
15+
16+
const localize = jest.fn(text => text);
17+
18+
const getAllowedLanguages = jest.fn(() => ({ EN: 'English', VI: 'Tiếng Việt' }));
19+
20+
const initializeI18n = jest.fn(() => {});
21+
22+
export { getAllowedLanguages, initializeI18n, Localize, localize, useTranslations };

babel.config.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
module.exports = {
2+
presets: [
3+
'@babel/preset-env',
4+
'@babel/preset-typescript',
5+
[
6+
'@babel/preset-react',
7+
{
8+
runtime: 'automatic',
9+
},
10+
],
11+
],
12+
plugins: [
13+
'syntax-dynamic-import',
14+
[
15+
'@babel/plugin-proposal-decorators',
16+
{
17+
legacy: true,
18+
},
19+
],
20+
[
21+
'@babel/plugin-proposal-class-properties',
22+
{
23+
loose: true,
24+
},
25+
],
26+
[
27+
'@babel/plugin-proposal-private-methods',
28+
{
29+
loose: true,
30+
},
31+
],
32+
[
33+
'@babel/plugin-proposal-private-property-in-object',
34+
{
35+
loose: true,
36+
},
37+
],
38+
'@babel/plugin-proposal-export-default-from',
39+
'@babel/plugin-proposal-object-rest-spread',
40+
'@babel/plugin-proposal-export-namespace-from',
41+
'@babel/plugin-syntax-dynamic-import',
42+
'@babel/plugin-proposal-optional-chaining',
43+
],
44+
};

babel.config.json

-14
This file was deleted.

jest.config.cjs

-11
This file was deleted.

jest.config.ts

+208
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
/**
2+
* For a detailed explanation regarding each configuration property, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
import type { Config } from 'jest';
7+
8+
const config: Config = {
9+
// All imported modules in your tests should be mocked automatically
10+
// automock: false,
11+
12+
// Stop running tests after `n` failures
13+
// bail: 0,
14+
15+
// The directory where Jest should store its cached dependency information
16+
// cacheDirectory: "/private/var/folders/sb/ck126x0n5zgf7g12_nb8gm0h0000gn/T/jest_dx",
17+
18+
// Automatically clear mock calls, instances, contexts and results before every test
19+
clearMocks: true,
20+
21+
// Indicates whether the coverage information should be collected while executing the test
22+
collectCoverage: true,
23+
24+
// An array of glob patterns indicating a set of files for which coverage information should be collected
25+
// collectCoverageFrom: undefined,
26+
27+
// The directory where Jest should output its coverage files
28+
coverageDirectory: 'coverage',
29+
30+
// An array of regexp pattern strings used to skip coverage collection
31+
coveragePathIgnorePatterns: ['/node_modules/'],
32+
33+
// Indicates which provider should be used to instrument code for coverage
34+
// coverageProvider: "babel",
35+
36+
// A list of reporter names that Jest uses when writing coverage reports
37+
// coverageReporters: [
38+
// "json",
39+
// "text",
40+
// "lcov",
41+
// "clover"
42+
// ],
43+
44+
// An object that configures minimum threshold enforcement for coverage results
45+
// coverageThreshold: undefined,
46+
47+
// A path to a custom dependency extractor
48+
// dependencyExtractor: undefined,
49+
50+
// Make calling deprecated APIs throw helpful error messages
51+
// errorOnDeprecated: false,
52+
53+
// The default configuration for fake timers
54+
// fakeTimers: {
55+
// "enableGlobally": false
56+
// },
57+
58+
// Force coverage collection from ignored files using an array of glob patterns
59+
// forceCoverageMatch: [],
60+
61+
// A path to a module which exports an async function that is triggered once before all test suites
62+
// globalSetup: undefined,
63+
64+
// A path to a module which exports an async function that is triggered once after all test suites
65+
// globalTeardown: undefined,
66+
67+
// A set of global variables that need to be available in all test environments
68+
// globals: {},
69+
70+
// 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.
71+
// maxWorkers: "50%",
72+
73+
// An array of directory names to be searched recursively up from the requiring module's location
74+
moduleDirectories: ['node_modules', 'bower_components', 'shared'],
75+
76+
// An array of file extensions your modules use
77+
// moduleFileExtensions: [
78+
// "js",
79+
// "mjs",
80+
// "cjs",
81+
// "jsx",
82+
// "ts",
83+
// "tsx",
84+
// "json",
85+
// "node"
86+
// ],
87+
88+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
89+
90+
moduleNameMapper: {
91+
'\\.(css|less|scss)$': '<rootDir>/__mocks__/styleMock.js',
92+
'\\.(gif|ttf|eot|svg)$': '<rootDir>/__mocks__/fileMock.js',
93+
'react-dom/server': '<rootDir>/__mocks__/react-dom-server.js',
94+
'@deriv-com/translations': '<rootDir>/__mocks__/translation.mock.js',
95+
'@deriv-com/ui': '<rootDir>/node_modules/@deriv-com/ui',
96+
'^@/external/(.*)$': '<rootDir>/src/external/$1',
97+
'^@/utils/(.*)$': '<rootDir>/src/utils/$1',
98+
'^@/components/(.*)$': '<rootDir>/src/components/$1',
99+
'^@/constants/(.*)$': '<rootDir>/src/constants/$1',
100+
'^@/hooks/(.*)$': '<rootDir>/src/hooks/$1',
101+
},
102+
103+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
104+
// modulePathIgnorePatterns: [],
105+
106+
// Activates notifications for test results
107+
// notify: false,
108+
109+
// An enum that specifies notification mode. Requires { notify: true }
110+
// notifyMode: "failure-change",
111+
112+
// A preset that is used as a base for Jest's configuration
113+
preset: 'ts-jest',
114+
115+
// Run tests from one or more projects
116+
// projects: undefined,
117+
118+
// Use this configuration option to add custom reporters to Jest
119+
// reporters: undefined,
120+
121+
// Automatically reset mock state before every test
122+
// resetMocks: false,
123+
124+
// Reset the module registry before running each individual test
125+
// resetModules: false,
126+
127+
// A path to a custom resolver
128+
// resolver: undefined,
129+
130+
// Automatically restore mock state and implementation before every test
131+
// restoreMocks: false,
132+
133+
// The root directory that Jest should scan for tests and modules within
134+
// rootDir: undefined,
135+
136+
// A list of paths to directories that Jest should use to search for files in
137+
// roots: [
138+
// "<rootDir>"
139+
// ],
140+
141+
// Allows you to use a custom runner instead of Jest's default test runner
142+
// runner: "jest-runner",
143+
144+
// The paths to modules that run some code to configure or set up the testing environment before each test
145+
setupFiles: ['<rootDir>/jest.setup.ts'],
146+
147+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
148+
// setupFilesAfterEnv: [],
149+
150+
// The number of seconds after which a test is considered as slow and reported as such in the results.
151+
// slowTestThreshold: 5,
152+
153+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
154+
// snapshotSerializers: [],
155+
156+
// The test environment that will be used for testing
157+
testEnvironment: 'jsdom',
158+
159+
// Options that will be passed to the testEnvironment
160+
// testEnvironmentOptions: {},
161+
162+
// Adds a location field to test results
163+
// testLocationInResults: false,
164+
165+
// The glob patterns Jest uses to detect test files
166+
// testMatch: [
167+
// "**/__tests__/**/*.[jt]s?(x)",
168+
// "**/?(*.)+(spec|test).[tj]s?(x)"
169+
// ],
170+
171+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
172+
// testPathIgnorePatterns: [
173+
// "/node_modules/"
174+
// ],
175+
176+
// The regexp pattern or array of patterns that Jest uses to detect test files
177+
// testRegex: [],
178+
179+
// This option allows the use of a custom results processor
180+
// testResultsProcessor: undefined,
181+
182+
// This option allows use of a custom test runner
183+
// testRunner: "jest-circus/runner",
184+
185+
// A map from regular expressions to paths to transformers
186+
transform: {
187+
'^.+\\.(ts|tsx)?$': 'babel-jest',
188+
'^.+\\.(js|jsx)$': 'babel-jest',
189+
'^.+\\.xml$': 'jest-transform-stub',
190+
},
191+
192+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
193+
transformIgnorePatterns: ['/node_modules/(?!@deriv-com/ui).+\\.js$'],
194+
195+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
196+
// unmockedModulePathPatterns: undefined,
197+
198+
// Indicates whether each individual test should be reported during the run
199+
// verbose: undefined,
200+
201+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
202+
// watchPathIgnorePatterns: [],
203+
204+
// Whether to use watchman for file crawling
205+
// watchman: true,
206+
};
207+
208+
export default config;

jest.setup.ts

+40-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,40 @@
1-
import '@testing-library/jest-dom/jest-globals';
2-
import '@testing-library/jest-dom';
1+
let originalLocalStorage: Storage;
2+
const localStorageMock: Storage = {
3+
clear() {
4+
this.store = {};
5+
},
6+
getItem(key) {
7+
return this.store[key];
8+
},
9+
key() {
10+
return 'test key';
11+
},
12+
length: 0,
13+
removeItem(key) {
14+
delete this.store[key];
15+
},
16+
setItem(key, value) {
17+
this.store[key] = value.toString();
18+
},
19+
store: {},
20+
};
21+
22+
export const mockLocalStorageBeforeEachTest = () => {
23+
originalLocalStorage = global.localStorage;
24+
Object.defineProperty(global, 'localStorage', { value: localStorageMock });
25+
};
26+
27+
export const restoreLocalStorageAfterEachTest = () => {
28+
Object.defineProperty(global, 'localStorage', { value: originalLocalStorage });
29+
};
30+
31+
Object.defineProperty(window, 'matchMedia', {
32+
writable: true,
33+
value: jest.fn().mockImplementation(query => ({
34+
matches: false,
35+
media: query,
36+
onchange: null,
37+
addListener: jest.fn(),
38+
removeListener: jest.fn(),
39+
})),
40+
});

0 commit comments

Comments
 (0)