使用 testcafe 监视 window 函数

Spy on window function with testcafe

我想用 testcafe 测试 window 对象上的函数是否使用某些参数执行。 Testcafe 有可能吗?

函数调用如下所示:

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

您可以使用 ClientFunction API 在 window 对象中创建间谍功能。请看下面的测试例子:

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