Reputation: 2926
I have this React application (cra
) which embeds a script in its header. I use React Helmet for that.
I.e., In App.js
I have this :
<GlobalContext.Provider>
<Helmet>
<script type="text/javascript" src={process.env.PUBLIC_URL + "/xmllint.js"}></script>
</Helmet>
<ThemeProvider theme={darkTheme}>
<Dashboard/>
</ThemeProvider>
</GlobalContext.Provider>
Anywhere in my typescript/javascript code, I have access to window.validateXML
which is the function declared in xmllint.js
.
(The reasons why I did this instead of an import
is because I never figured out how to make this raw import play nice with the rest of the toolchain, and after trying for 3 days straight, I went with this option which is ugly but works).
However, when writing tests with Jest, the framework somehow does not see this global import, no matter how I tweak it.
C:\Users\me\source\ [unit_test ≡ +0 ~2 -0 !]> npm t -- --watchAll=false --json --outputFile=results.json
FAIL src/tests/MyTest.test.js (6.3 s)
● has access to validateXML
TypeError: validateXML is not a function
50 | // XSD validation
51 | const xsd = await(await fetch('Test.xsd')).text()
> 52 | const res = validateXML({
| ^
53 | xml:fileContent,
54 | schema: xsd,
55 | arguments: ["--noout", "--schema", 'Test', fileName]
at ParseInputFile (src/Logic.tsx:52:14)
at uploadXML (src/Logic.tsx:138:17)
This is what the test looks like
it('has access to validateXML', async () => {
const user = userEvent.setup()
render(
<GlobalContext.Provider>
<Helmet>
<script type="text/javascript" src={"/xmllint.js"}></script>
</Helmet>
<Router>
<MyComponentThatAccessesValidateXML>
</Router>
</GlobalContext.Provider>
)
let fileUploadButton = screen.getByRole('button', {name:'Upload XML'})
const file = new File([xmlScenario], 'scenario.xml', {type: 'application/xml'})
expect(fileUploadButton).toBeVisible()
await waitFor(() => user.upload(fileUploadButton, file))
})
So the script is added to the header just like in App.js
.
Things I have tried :
src
to point to the location of xmllint.js
relatively to the current filesrc
to xmllint.js
src
to /xmllint.js
xmllint.js
via import
or require
import {validateXML} from "xmllint"
import validateXML from "xmllint"
import {validateXML} from "xmllint.js"
import {validateXML} from "xmllint.js"
import {validateXML} from "../../public/xmllint"
import {validateXML} from "../../public/xmllint.js"
const validateXML = require("xmllint.js")
const validateXML = require("xmllint")
const validateXML = require("../../public/xmllint")
const validateXML = require("../../public/xmllint.js")
undefined
.What can I do so my test sees the import validateXML
that should be available globally ?
Upvotes: 0
Views: 30