Я пытаюсь создавать динамические тесты на основе таблицы Excel с помощью testcafe, используя TypeScript. Это работает гладко... пока я не попытаюсь динамически создавать «тесты» «приспособления».
Мой код:
import { fixture, test, GFunctions } from './index';
fixture`API Testing with TestCafe`
.page`about:blank`;
// Assume testData is an array of test definitions
let gFunctionName: any = getFunctionName()
const testData: any = await getTestData(gFunctionName)
console.info(testData)
for (const data of testData) {
test(`APITest: ${data.gFunctionName}`, async (t) => {
// Initialisations
const { token }: { token: any; } = await GFunctions.getAccessToken(t, gFunctionName);
// const gfuctionResponse: any = await GFunctions.getParamsAndExecute(data.index, data.response, t, token, gFunctionName);
// console.info('\x1b[31m%s\x1b[0m', `Status: ${gfuctionResponse.status} >> ${data.result_status}`);
});
}
function getFunctionName() {
return GFunctions.getGFunctionName(\__filename)
}
async function getTestData(gFunctionName: string) {
const { testData }: { testData: any } = await GFunctions.getTestDefinition(gFunctionName);
return testData;
}
Когда я запускаю код, я всегда получаю следующую ошибку:
ERROR Cannot prepare tests due to the following error:
Error: TypeScript compilation failed.
D:/Repositories/WAS_API-Testing/TestCafe/environments/fo-wastest-eshop-regression.was.local/tests/_gGetGlobalConfigVar.apitest.ts (9, 23):
Top-level 'await' expressions are only allowed when the 'module' option is set to
'es2022', 'esnext', 'system', 'node16', or 'nodenext',
and the 'target' option is set to 'es2017' or higher.
пакет.json:
{
"type": "module",
"name": "testcafe-tests",
"description": "TestCafe-Tests",
"version": "24.01.0",
"scripts": {
"TEST": "testcafe chrome:headless tests/_gGetGlobalConfigVar.apitest.ts --ts-config-path=./tsconfig.test.json -r spec,xunit:./reports/report.apitest.xml,html:reports/report.apitest.html"
},
"dependencies": {
"exceljs": "^4.4.0",
"testcafe-reporter-html": "^1.4.6"
},
"devDependencies": {
"testcafe": "^3.6.0"
},
"volta": {
"node": "16.13.1"
}
}
tsconfig.json
{
"compilerOptions": {
// "target": "ES6",
"module": "CommonJS",
"strict": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": false,
"esModuleInterop": true
},
"include": [
"../../opacc_modules/"
]
}
tsconfig.test.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"strict": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": false,
"esModuleInterop": true,
"moduleResolution": "node"
},
"include": [
"**/*.apitest.ts"
]
}
Есть ли у кого-нибудь идеи, как это решить? Насколько я понимаю, я использую упомянутый объект/модуль...?
С надеждой Римский
You cannot override the "target" compiler option in the TypeScript configuration file.
You cannot override the "module" compiler option in the TypeScript configuration file.
Сообщения об ошибках обычно полезны:
Выражения «await» верхнего уровня разрешены только в том случае, если для параметра «module» установлено значение «es2022», «esnext», «system», «node16» или «nodenext», а для параметра «Цель» установлено значение «es2017» или выше.
Просто следуйте инструкциям. Измените свои tsconfig.json
.
Я сделал. Но потом, как уже упоминалось, я получил это сообщение
Вы не можете переопределить параметр компилятора «target» в файле конфигурации TypeScript. Вы не можете переопределить параметр компилятора «модуль» в файле конфигурации TypeScript.
Как упоминалось в сообщении, вы не можете переопределить параметры компилятора «цель» и «модуль» в TestCafe.
Но чтобы использовать выражения ожидания верхнего уровня, подобные вашему
(const testData: any = await getTestData(gFunctionName))
,
вы можете обернуть вызов getTestData
в выражение немедленно вызываемой функции.
https://developer.mozilla.org/en-US/docs/Glossary/IIFE#execute_an_async_function
Это сработало. К сожалению, кажется, что - когда на верхнем уровне нет подпрограмм test(), Testcafe просто полностью игнорирует код - Попробую еще немного. Если я не смогу запустить его, я создам основной тест и выполню тестовые данные в нем целиком. Спасибо
попробую это! Спасибо :)