如何在 Cypress 中测试以某种形状的对象作为参数调用的存根函数?

Bro*_*hen 3 javascript testing cypress

如何测试是否使用特定形状的对象作为参数来调用存根函数?

例如,我试图做类似的事情

cy.get('@submitStub').should('have.been.calledWithMatch', {
  dateRange: {
    startDate: `The actual value here doesn't matter`,
    endDate: '',
  }
});
Run Code Online (Sandbox Code Playgroud)

当然,上面的代码并不能按预期工作。有人可以帮忙吗?谢谢你!

dwe*_*lle 6

你可以做:

describe('test', () => {
  it('test', () => {
    const obj = {
      method () {}
    };
    cy.stub(obj, 'method').as('stubbed')

    obj.method({
      dateRange: {
        startDate: `The actual value here doesn't matter`,
        endDate: '',
      }
    });

    const isNotUndefined = Cypress.sinon.match( val => {
      return val !== undefined;
    });

    cy.get('@stubbed').should('have.been.calledWithMatch', {
      dateRange: {
        startDate: isNotUndefined,
        endDate: isNotUndefined,
      }
    });

    // or
    cy.get('@stubbed').should('have.been.calledWithMatch', {
      dateRange: Cypress.sinon.match( obj => {
        return obj &&
          'startDate' in obj &&
          'endDate' in obj
      })
    });

    // or
    cy.get('@stubbed').should('have.been.calledWithMatch', {
      dateRange: Cypress.sinon.match.has("startDate")
        .and(Cypress.sinon.match.has("endDate"))
    });

    // or
    cy.get('@stubbed').should('have.been.calledWithMatch', arg1 => {
      // do whatever comparisons you want on the arg1, and return `true` if 
      //  it matches
      return true;
    });
  });
});
Run Code Online (Sandbox Code Playgroud)