Search code examples
javascriptautomated-testse2e-testingweb-testingtestcafe

TestCafe persist data when clicking


In TestCafe, on click of an anchor tag, I have a redirect to a new page and an event that basically logs the click event to an object.

I'm wanting to test the value of the click event in the object in TestCafe, but because the redirect happens, I lose the object.

Manually I'm able to do this, as I can hold shift while clicking the link and open a new window for the redirected page, but keep the original page in the original window and then see the object in the console.

Trying to figure out if there's a way "simulate" a click, but not do the redirect. Or alternatively, be able to assert somehow immediately after the click, but before the redirect?

mini example:

await t
.click('a') // here it already redirects so I'll lose the object
.expect(object).contains('value')

Solution

  • The following test shows how you can disable and enable navigation for a link:

    import { Selector, ClientFunction } from 'testcafe';
    
    fixture `Navigation`
        .page `example.com`;
    
    const enableNavigationControl = ClientFunction(selector => {
        const element = selector();
    
        element.addEventListener('click', event => window.disableNavigation && event.preventDefault());
    });
    
    const disableNavigation = ClientFunction(() => window.disableNavigation = true);
    const enableNavigation  = ClientFunction(() => window.disableNavigation = false);
    
    test('navigation', async t => {
        const link = Selector('a');
    
        await enableNavigationControl(link);
        await disableNavigation();
    
        await t.click(link);
    
        // Perform assertions...
    
        await enableNavigation();
    
        await t.click(link);
    });