Search code examples
javascriptnode.jsbddmocha.jsuser-stories

Mocha: Translating a user story to a spec of describe / it (bdd framework i.e. mocha)?


I am trying to convert/translate my user stories into mocha specs using describe and it. I am finding it a little confusing.

Give an example story:

Story: Account Holder withdraws cash

As an Account Holder
I want to withdraw cash from an ATM
So that I can get money when the bank is closed

Scenario 1: Account has sufficient funds
Given the account balance is \$100
 And the card is valid
 And the machine contains enough money
When the Account Holder requests \$20
Then the ATM should dispense \$20
 And the account balance should be \$80
 And the card should be returned

Scenario 2: Account has insufficient funds
Given the account balance is \$10
 And the card is valid
 And the machine contains enough money
When the Account Holder requests \$20
Then the ATM should not dispense any money
 And the ATM should say there are insufficient funds
 And the account balance should be \$20
 And the card should be returned

So using mocha's "describe" and "it", what would be the best way of translating this. Most of the examples I have seen use BDD in a way that tests the functions and methods - which really feels more like TDD to me.

Edit

I also want to use mocks; if I translate the user story exactly then would I be able to mocks?


Solution

  • I am not very familiar with mocha so I did a similar one for you. Hope you get the idea.

    Scenario 1:

    it should authenticate card currectly if a valid card and details are provided:
    System.readCard(new Card({config}))....
    expect(System.Card.isValid).toBe(true)
    
    it should get the correct financial details from the user 
    // You know it's your card and you have $100
    var originalBalance = System.User.Balance;
    expect(originalBalance).to.be(100);
    
    it should have enough for the user
    System.User.RequestBalance = 20;
    expect(System.Vault.Balance).to.be.at.least(System.User.RequestBalance);
    
    it should dispense the requested amount:
    System.Dispence(System.User.RequestBalance);
    expect(System.Vault.Balance).to.be(System.Vault.Balance - System.User.RequestBalance);
    
    it should deduct the amount from user's account
    expect(System.User.Balance).to.be(originalBalance - System.User.RequestBalance);
    
    it should return the card
    Syste.ejectCard();
    expect(System.CardHolder.isEmpty).to.be(true);
    

    ....and so on. This is just a quick one to give you an idea.

    Note that the general idea is that you do something and you make an assertion towards the outcome and check whether that thing that if it happens it proves what you want is the case has actually happened.