I have a tool for asynchronously loading scripts, using jest for asynchronous testing, but jest has timed out and can't respond to scripts. How do I implement this feature?
Steps to reproduce the behavior: Execute it according to the code I provided.
I want to get a response in the on tag event of the script tag, in fact the onload event is not fired.
let AMap = null
const defaultPath = 'https://webapi.amap.com/maps'
function mapLoader(key, version, url) {
return new Promise((resolve, reject) => {
const aMapUrl = `${defaultPath}?v=${version}&key=${key}`
const jsApi = document.createElement('script')
jsApi.charset = 'utf-8'
jsApi.src = aMapUrl
jsApi.onerror = reject
jsApi.onload = () => {
if (window.AMap) {
resolve(window.AMap)
} else {
warn('AMap SDK Load Failure.')
}
}
document.head.appendChild(jsApi)
})
}
test('test mapLoader function', () => {
return mapLoader('d2d76e2274bf5973ecfb1f68454b6f3b', '1.4.15').then(
AMap => {
expect(AMap).toEqual(expect.anything())
}
)
})
npx envinfo --preset jestPaste the results here: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
Of its time intensive, increase the timeout
The problem is that inserting script tags does not respond to onload events, and adding timeouts is not a solution.
It's an issue with JSDOM then, not Jest. Please search for something similar on their issue tracker or make a detailed bug report there :)
Or better, use a real browser for testing: https://github.com/smooth-code/jest-puppeteer