Add the capability to execute a custom script before page initialization scripts
Are you requesting a feature or reporting a bug?
feature suggestion
What is the current behavior?
TestCafe executes a ClientFunction when the page is fully loaded.
What is the expected behavior?
Add ability to execute any client script in the browser before other page scripts.
Here are some use cases: Catch JS errors and console output Executing code in the browser before the page code evaluates
Proposed API:
import fs from 'fs';
const initializationScript = fs.readFileSync('./script.js').toString()
fixture `My fixture`
.addScriptToEachPage(initializationScript);
test
.addScriptToEachPage(initializationScript);
Feel free to vote for the feature if you consider it useful and please let us know about your use case for it.
This feature is useful e.g. if you want to override console.log to spy on console output in your tests.
Yes. This feature is good
@AlexanderMoskovkin
I think that ClientFunction support will be useful for this feature:
test.addScriptToEachPage(ClientFunction(...));
I would suggest to extend the proposal with several points made in #2234:
-
Multiple asset types (scripts, styles, fonts), useful for UI/visual regression testing or any cases that would require to apply test-related changes to application code otherwise
-
Multiple asset insertion positions (
startandendofheadandbody), with end of document body as default value -
'Here and now' asset insertion position for fixture/test assets, a shortcut for
t.eval () => { document.createElement... }, also accepts a ClientFunction -
Local assets that are resolved from NPM module name or relative path, a shortcut for
fs.readFileSync('require.resolve('module'), 'utf8')(currently included as is, no bundling or transpilation) -
Remote CDN assets identified by URL
-
Fixture assets
-
Test assets
-
Global assets for entire test run (similar to Karma
files) as runner and CLI options
Currently the framework has undocumented embeddingOptions runner method, it makes an asset (script or style) being served by TestCafe server, is available only on runner init but not in CLI. Another part of the process is internal testRun.injectable property that allows to push served script/style to <head>, it seems to be reachable in specs as t.testRun.injectable but is unavailable on runner init.
This would also be helpful if certain local storage keys need to be set before the page loads.
Note: we already have build-in support for accessing console messages
any update for this enhancement?
Hi @juliusgonawan
Would you please describe a real life case for which you need this functionality?
@miherlosev
A real world escenario i've found is avoiding a service worker registration. If a service worker is registered without using https, chrome logs a console error which forces you to run testcafe with the -e flag. I'd like to run testcafe without ignoring Js Error messages.
Service worker are usually registered with an inline script:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
</script>
So if i try to mock navigator.serviceWorker in the test, it will be mocked after the script has run.
@miherlosev
A real world scenario is mine. I want to use PollyJS to record/mock some xhr or fetch requests. But to do so, I have to inject it into the page early. I tried it with ClientFunction, but it injects too late, so it missed some requests. An option to inject code as early as possible would be fine.
@NickCis, @bitjoo - thank you for providing additional details. You can solve these issues by using RequestMock to handle specific page requests. Take a look at the following topics in the documentation:
For example, you can mock a service worker script for browsers that don't support this feature using the following code:
import { ClientFunction, RequestMock } from 'testcafe';
const supportsServiceWorkers = ClientFunction(() => 'serviceWorker' in navigator);
fixture `ServiceWorker`
.page('http://my-site.com')
.beforeEach(async t => {
const canUseServiceWorkers = await supportsServiceWorkers();
if (canUseServiceWorkers)
return;
await t.addRequestMocks(
RequestMock()
.onRequest('http://my-site.com/service-worker.js')
.respond('');
);
});
@miherlosev One more use case is that. Since client scripts are loading after page load, we can not mock any setInterval, setTimout functions
I think this issue fits in my case as well, as I would like to use axe-core within my tests - and as this requires the library to be run within browser client, i think it fits. I can see that it's now in the roadmap which is great, but perhaps there could be some neat workaround to achieve it? I wouldn't like to hack in a way that I'll store the dist of the axe-core somewhere, then load it in the runtime, hope it loads and then run a test 🤔
@Worie, I guess you can use axe-core with TestCafe without the suggested feature. Please check a demo project made by @helen-dikareva, which integrates axe with TestCafe: https://github.com/helen-dikareva/axe-testcafe
I would also love to have this ability, especially to be able to use normal npm modules that use module.exports' or export` to expose functions etc.
Also should be possible to specify an initialization script on the test run level (see https://github.com/DevExpress/testcafe/issues/3857).
const runner = testcafe.createRunner();
return runner
.src(['tests/fixture1.js', 'tests/func/fixture3.js'])
.browsers(['chrome', 'safari'])
.addScriptToEachPage(initializationScript)
.run();
Don't you think we should be able to do this without having to create a custom runner script?
Could you please describe your test case in greater detail? We need this information to design our API as much flexible as possible.
@helen-dikareva if you look at @miherlosev's example above, the other options (src, browser, etc) are all options you can set in the testcafe config file. What I'm saying, is that we should also be able to specify the addScriptToEachPage in the config as well, so we can continue using the config file (which is lovely).
-Ben
@benmonro Thank you for the description. If we decide to implement @miherlosev's suggestion we will consider your suggestion as well.