|
| 1 | +/** |
| 2 | + * Copyright (c) Hathor Labs and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +import * as path from 'path'; |
| 9 | + |
| 10 | +// eslint-disable-next-line import/no-extraneous-dependencies |
| 11 | +const NodeEnvironment = require('jest-environment-node').TestEnvironment; |
| 12 | + |
| 13 | +/** |
| 14 | + * Extracts the test name from an absolute path received by the context |
| 15 | + * @param {string} filePath Absolute path |
| 16 | + * @returns {string} Test filename without directories, test suffixes or extensions |
| 17 | + * @example |
| 18 | + * const name = getTestName('/home/user/code/address-info.test.js') |
| 19 | + * assert(name == 'address-info') |
| 20 | + */ |
| 21 | +function getTestName(filePath) { |
| 22 | + const baseName = path.basename(filePath); |
| 23 | + const extName = path.extname(filePath); |
| 24 | + |
| 25 | + return baseName.replace(`.test${extName}`, ''); |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * This custom environment based on the Node environment is used to obtain the test name that is |
| 30 | + * currently being executed, an important piece of information used on `setupTests-integration.js`. |
| 31 | + * @see https://jestjs.io/docs/configuration#testenvironment-string |
| 32 | + */ |
| 33 | +export default class CustomEnvironment extends NodeEnvironment { |
| 34 | + /** |
| 35 | + * The testname is obtained from the constructor context |
| 36 | + * @param config |
| 37 | + * @param context |
| 38 | + */ |
| 39 | + constructor(config, context) { |
| 40 | + super(config, context); |
| 41 | + this.testName = getTestName(context.testPath); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * The local testname is injected on the global environment for this specific test on setup |
| 46 | + * @returns {Promise<void>} |
| 47 | + */ |
| 48 | + async setup() { |
| 49 | + await super.setup(); |
| 50 | + this.global.testName = this.testName; |
| 51 | + } |
| 52 | + |
| 53 | + /* |
| 54 | + * For debugging purposes, some helper methods can be added to this class, such as: |
| 55 | + * - getVmContext() |
| 56 | + * - teardown() |
| 57 | + * - runScript(script) |
| 58 | + * - handleTestEvent(event) |
| 59 | + * |
| 60 | + * @see https://jestjs.io/docs/configuration#testenvironment-string |
| 61 | + */ |
| 62 | +} |
0 commit comments