testcafe icon indicating copy to clipboard operation
testcafe copied to clipboard

Add the capability to execute a custom script before page initialization scripts

Open AlexanderMoskovkin opened this issue 9 years ago • 32 comments

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.

AlexanderMoskovkin avatar Aug 29 '17 14:08 AlexanderMoskovkin

This feature is useful e.g. if you want to override console.log to spy on console output in your tests.

dimaip avatar Aug 30 '17 07:08 dimaip

Yes. This feature is good

CommanderXL avatar Aug 31 '17 03:08 CommanderXL

@AlexanderMoskovkin

I think that ClientFunction support will be useful for this feature:

test.addScriptToEachPage(ClientFunction(...));

San4es avatar Sep 18 '17 15:09 San4es

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 (start and end of head and body), 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.

bisubus avatar Mar 22 '18 14:03 bisubus

This would also be helpful if certain local storage keys need to be set before the page loads.

craig-jennings avatar Jun 13 '18 21:06 craig-jennings

Note: we already have build-in support for accessing console messages

miherlosev avatar Aug 15 '18 10:08 miherlosev

any update for this enhancement?

juliusgonawan avatar Nov 06 '18 07:11 juliusgonawan

Hi @juliusgonawan

Would you please describe a real life case for which you need this functionality?

miherlosev avatar Nov 06 '18 08:11 miherlosev

@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.

NickCis avatar Nov 06 '18 19:11 NickCis

@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.

bitjoo avatar Nov 15 '18 08:11 bitjoo

@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('');
         );
     });

AndreyBelym avatar Nov 16 '18 14:11 AndreyBelym

@miherlosev One more use case is that. Since client scripts are loading after page load, we can not mock any setInterval, setTimout functions

samsoft05 avatar Nov 25 '18 18:11 samsoft05

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 avatar Mar 01 '19 14:03 Worie

@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

AndreyBelym avatar Mar 04 '19 11:03 AndreyBelym

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.

benmonro avatar Apr 24 '19 22:04 benmonro

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();

miherlosev avatar Jun 03 '19 13:06 miherlosev

Don't you think we should be able to do this without having to create a custom runner script?

benmonro avatar Jun 03 '19 18:06 benmonro

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 avatar Jun 04 '19 15:06 helen-dikareva

@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 avatar Jun 04 '19 19:06 benmonro

@benmonro Thank you for the description. If we decide to implement @miherlosev's suggestion we will consider your suggestion as well.

AlexKamaev avatar Jun 05 '19 08:06 AlexKamaev