Problem:
I am trying to add a field to the global object during the test run
global-setup.ts
module.exports = async (config, projectConfig) => {
...
global.someone = 1;
...
};
testfile.test.ts
describe('sometitle', ()=>{
test('testTitle', () => {
try{
console.log(global.someone) // 1;
expect(false).toBe(true);
} catch (e) {
global.sometwo = 2;
throw(e);
}
})
})
global-teardown.ts
module.exports = async function (globalConfig, projectConfig) {
...
console.log(global.someone); // 1
console.log(global.sometwo); // undefined
...
}
The ‘sometwo’ field that initiates during the test run is undefined while running the global teardown.
The global setup/teardown should run once for all test suites.
Any ideas?
Solution:
Create a configuration file, e.g.:
// testConfig.js
module.exports = {
someone: 1,
};
Update your global setup to load this configuration:
// global-setup.ts
const testConfig = require('./testConfig');
module.exports = async (config, projectConfig) => {
global.testConfig = testConfig;
};
Modify your test to access the configuration
// testfile.test.ts
describe('sometitle', () => {
test('testTitle', () => {
try {
console.log(global.testConfig.someone); // 1;
expect(false).toBe(true);
} catch (e) {
global.testConfig.sometwo = 2;
throw e;
}
});
});