Jest.js 如何在测试运行期间向全局对象添加字段?

fiei3ece  于 8个月前  发布在  Jest
关注(0)|答案(1)|浏览(75)

我正在尝试在测试运行期间向全局对象添加字段
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
...
}


在运行全局拆卸时,未定义在测试运行期间启动的“sometow”字段。
对于所有测试套件,全局设置/拆卸应运行一次。
有什么想法吗?

axr492tv

axr492tv1#

创建配置文件,例如:

// testConfig.js
module.exports = {
  someone: 1,
};

字符串
更新全局设置以加载此配置:

// global-setup.ts
const testConfig = require('./testConfig');

module.exports = async (config, projectConfig) => {
  global.testConfig = testConfig;
};


修改测试以访问配置

// 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;
    }
  });
});

相关问题