0

script tag is not available while doing jest testing

public/index.html content

script src="config.js" //script tag

public/config.js content

window.appConfig = {
    oboServicePath: 'some path'
}

axios.ts

const axiosOBOInstance = axios.create({
    // @ts-ignore
    adapter: cacheAdapterEnhancer(axios.defaults.adapter, {
    defaultCache,
}),
baseURL: appConfig.getRequired('oboServicePath'),

Error at

appConfig.getRequired as window.appConfig is undefined

appConfig should be available @window scope.

1 Answer 1

1

Jest just runs the code in the unit tests and doesn't know about the script tags in index.html.

appConfig will need to be added to window as part of the setup for the unit tests.

It looks like public/config.js contains setup code that should run before every test.

If you are using Jest by itself you can tell Jest to run public/config.js before every test using setupFiles or setupTestFrameworkScriptFile.

If you are using create-react-app then create src/setupTests.js if it doesn't already exist (src/setupTests.ts if you are using TypeScript) and add your setup code. That file "will be automatically executed before running your tests".

Sign up to request clarification or add additional context in comments.

3 Comments

Getting error - react-scripts-ts test --env=jsdom --coverage "AppHeaderView.test.tsx" Out of the box, Create React App only supports overriding these Jest options: • collectCoverageFrom • coverageReporters • coverageThreshold • snapshotSerializers • moduleNameMapper. These options in your package.json Jest configuration are not currently supported by Create React App: • setupFiles If you wish to override other Jest options, you need to eject from the default setup. I do not want to eject the project... so do we have any other options.
@sunilsharma I added details about adding setup code to an app bootstrapped with create-react-app
this does not solve the problem though, which is that code in script tags is not called, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.