I have an API request that returns some tokens I need for most requests. I’ve placed a function in a setupFiles
, and declared a variable using global.varName
. I attempt to use the variable in a beforeEach()
hook. But when I run Jest, before loading context, or executing the file in setupFiles
, I get an error that the variable is not a function.
Background – This is an old MVC app, all data is embedded in html. I am using Cheerio library for easier parsing.
Note: I have abstracted fetch http handler for re-usability, omitting that code.
jest.config.cjs
const jestConfig = {
testMatch: ['**/tests/*.cjs'],
setupFiles: ['./tests/lib/auth.cjs'],
globals: {
baseUrl: 'https://someUrl.com/',
}
};
module.exports = jestConfig;
relevant function in auth.cjs
async function getReqVerificationValues() {
const getCreateScriptScreen = await get(
'someUri'
);
expect(getCreateScriptScreen.status).toBe(200);
const getCreateScriptScreenText = await getCreateScriptScreen.text();
global.createScriptDom = cheerio.load(getCreateScriptScreenText);
}
module.exports = { getReqVerificationValues };
Relevant section of scripts.test.cjs
:
beforeEach(() => {
const prescriberIdList = global
.createScriptDom('[id=PrescriberId]')
.children()
.match(/(?<=option value=")(?!s*$).+(?=")/g);
});
Error Message:
TypeError: global.createScriptDom is not a function