jest-cucumber icon indicating copy to clipboard operation
jest-cucumber copied to clipboard

Re-using step definitions not working (always undefined)

Open theprobugmaker opened this issue 3 years ago • 5 comments

I'm trying to re-use the steps but when I try to log the myAccount variable on the test function it's always undefined, and passing it forward as argument it gives me errors saying I can't call methods from undefined. (https://github.com/bencompton/jest-cucumber/blob/master/docs/ReusingStepDefinitions.md)

The easiest way to see this problem is to console.log(myAccount) here: https://github.com/bencompton/jest-cucumber/blob/1a9ef75f5602d5b18dd4b33d08130e878799da59/examples/typescript/specs/step-definitions/using-dynamic-values.steps.ts#L14

How can I solve this? Thank you.

theprobugmaker avatar May 15 '21 16:05 theprobugmaker

cc @bencompton

theprobugmaker avatar May 16 '21 15:05 theprobugmaker

same here.

cbezmen avatar Jun 03 '21 14:06 cbezmen

Hi @zefexdeveloper I figured out the solution to use shared steps. You can use callback to send account to shared steps.

Example:

// shared-steps.js
	
export const givenIHaveXDollarsInMyBankAccount = (given, accountCallback) => {
  given(/I have \$(\d+) in my bank account/, balance => {
    accountCallback().deposit(balance);
  });
};

export const thenMyBalanceShouldBe = (then, accountCallback) => {
  then(/my balance should be \$(\d+)/, balance => {
    expect(accountCallback().balance).toBe(parseInt(balance));
  });
};
// example.steps.js

import { thenMyBalanceShouldBe, givenIHaveXDollarsInMyBankAccount } from './shared-steps';

defineFeature(feature, test => {
  let myAccount;
		
  beforeEach(() => {
    myAccount = new BankAccount();
  });

  test('Making a deposit', ({ given, when, then }) => {
    givenIHaveXDollarsInMyBankAccount(given, () => myAccount);

    when(/I deposit \$(\d+)/, deposit => {
      myAccount.deposit(deposit);
    });

    thenMyBalanceShouldBe(then, () => myAccount);
  });
	
  test('Making a withdrawal', ({ given, when, then }) => {
    givenIHaveXDollarsInMyBankAccount(given, () => myAccount);

    when(/I withdraw \$(\d+)/, withdrawal => {
      myAccount.withdraw(withdrawal);
    });		

    thenMyBalanceShouldBe(then, () => myAccount);
  });
});

cbezmen avatar Jun 04 '21 05:06 cbezmen

@cbezmen That is lovely, thank you very much

theprobugmaker avatar Jun 13 '21 00:06 theprobugmaker

fixed #135

cbezmen avatar Jun 30 '21 16:06 cbezmen