Search code examples
testingautomationautomated-testse2e-testingtestcafe

Spy on window function with testcafe


I want to test with testcafe if a function on a window object is executed with certain parameters. Is it possible with Testcafe?

The function call looks like this:

window.myObject.myFunction({customObject: true});

Solution

  • You can use the ClientFunction API to create a spy function in a window object. Please look at the following test example:

    import { ClientFunction } from 'testcafe';
    
    fixture `New Fixture`
        .page `https://cf51n.csb.app/`;
    
    const spyOn = ClientFunction(() => {
      // Create an array where we store information about `myFunction` calls
      window.myFunctionSpyData = [];
    
      // Store the original `myFunction` value
      window.orirginalFunction = window.myObject.myFunction;
    
      
      window.myObject.myFunction = function() {
        // Save data about the current call
        window.myFunctionSpyData.push(...arguments);
    
        // Call the original `myFunction` value
        window.orirginalFunction(...arguments);
      }
    });
    
    const getSpyData = ClientFunction(() => {
      // Retrieve data about myFunction calls from client
      return window.myFunctionSpyData;
    });
    
    const spyOff = ClientFunction(() => {
      // Restore the original myFunction value
      window.myObject.myFunction = window.orirginalFunction;
      delete window.spyData;
    });
    
    test('New Test', async t => {
        await spyOn();
    
        await t.click('#btn');
    
        const data = await getSpyData();
        await spyOff();
    
        await t
            .expect(data.length).eql(2)
            .expect(data[0]).eql('1')
            .expect(data[1]).eql('2');
    });