我正在尝试使用Jest的test.each()
功能动态创建一组测试。
首先,我必须通过异步函数设置变量,这在Jest中似乎很棘手。当在beforeAll()中设置变量时,为时已晚,执行test.each()
时变量为undefined。
因此,我尝试使用此globalSetup
中提到的asnwer选项。但是在调试时,全局变量也显示为未定义的奇数。
有没有办法在Jest中将此类变量传递给参数化测试?
describe.only('Param tests', () => {
test.each(global.__sites__)('Params', (host) => {
console.log(host);
});
});
//setup.js
const Loader = require('./Loader.js');
module.exports = async () => {
await Loader.getSites().then(data => {
global.__sites__ = data.filter(record => record.length > 4);
});
};
//jest.config.js
module.exports = {
testTimeout: 20000,
setupFilesAfterEnv: ["expect-puppeteer"],
globalSetup: "./setup.js"
};
您应该使用setupfilesafterenv而不是globalSetup配置。如果要在每个测试用例/套件和测试文件中获取global.__sites__
。
这里是使用globalSetup
配置的注释:
通过globalSetup定义的任何全局变量只能在globalTeardown中读取。您无法在测试套件中检索此处定义的全局变量。
这意味着您只能在分配给global.__sites__
配置的文件中获取globalteardown的值。在测试用例中访问undefined
时,将获得global.__sites__
。