Search code examples
javascriptnode.jstestinge2e-testingtestcafe

TestCafe: How to test logout if user logged in from another machine


I have a scenario where I want to start running a test on chrome and at specific point I want my test to open different browser (firefox) and to do the same steps as in chrome then go back to chrome again and verify a change in ui. Is there anyway to do this using testcafe?


Solution

  • I am glad I asked.

    In order to test if a login in another browser triggers a logout in the current browser, there is no need to run a different browser. You can send the according login command from your test code.

    node.js builtin standard http library is sufficient for that task. The official documentation has a specific section on http requests: https://nodejs.org/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request/

    I personally prefer the fetch API as available in the browser. node-fetch provides this API in node.

    so your test code could look a little like this:

    import 'node-fetch';
    import { URLSearchParams } from 'url';
    
    // we assume we get page state and interaction from this seperate module
    import { loginAction, getIsLogged } from './page-actions';
    
    fixture `login logut`
        .page `http://your.app/`;
    
    test('User is logged out if logged in somewhere else', async t => {
        // perform the login actions to login as "username"
        await loginAction(t, 'yourUsername', 'yourPassword');
        
        await simulateLoginFromSomewhereElse('yourUsername', 'yourPassword');
    
        await t.expect(getIsLoggedIn(t)).eql(false);
    });
    
    async function simulateLoginFromSomewhereElse(username, password) {
        // build the (form) data to be sent to the server
        const params = new URLSearchParams();
        params.append('username', 'yourUsername');
        params.append('password', 'yourPassword');
    
        await fetch(`http://your.app/login`, { method: 'POST', body: params });
    }