Mocha: переводить пользовательскую историю в спецификацию описать / это (bdd framework т.е. mocha)?
Я пытаюсь преобразовать / перевести мои пользовательские истории в спецификации mocha usign description и это....
Я нахожу это немного запутанным, кто-нибудь может помочь?
Приведите пример истории:
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
Так что, используя слова "описать" и "это", можно найти лучший способ перевести это. Большинство примеров, которые я видел, используют BDD таким образом, чтобы тестировать функции и методы - что для меня действительно больше похоже на TDD.
Любая помощь действительно ценится.
РЕДАКТИРОВАТЬ
Также желая использовать насмешки, если я перевожу историю пользователя именно тогда, я смогу издеваться, не так ли?
Я что-то здесь упускаю:-)
2 ответа
Я не очень знаком с мокко, поэтому я сделал аналогичный для вас. Надеюсь, вы поняли идею. (Люди, пожалуйста, заполните бесплатно, чтобы улучшить его)
Senario 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);
.... и так далее... просто быстрый, чтобы дать вам идею, извините, не могу сделать все это на работе;)
Обратите внимание, что общая идея заключается в том, что вы делаете что-то, и вы делаете утверждение в отношении результата и проверяете, действительно ли эта вещь, если она случается, доказывает, что вы хотите, действительно произошла.
Я немного опаздываю на вечеринку, но в случае, если у кого-то еще есть подобная потребность. У меня есть библиотека мокко, которая предоставляет очень богатый синтаксис Gherkin aka Feature/Scenario/Given/When/Then и т.д. Вы можете найти проект здесь:
https://github.com/dotnetprofessional/LiveDoc/tree/master/packages/livedoc-mocha
Пример, который выглядит так:
feature(`Account Holder withdraws cash
Account Holders should be able to withdraw cash at any of the
companies ATMs.
Rules:
* Account Holders should have a valid keycard
* Have sufficient available funds
* The ATM has the necessary funds
`, () => {
scenario("Account has sufficient funds", () => {
let atm = new ATM();
let cashReceived: number;
given(`the account holders account has the following:
| account | 12345 |
| balance | 100 |
| status | valid |
`, () => {
const accountHolder = stepContext.tableAsEntity;
atm.setStatus(accountHolder.account, accountHolder.status);
atm.deposit(accountHolder.account, accountHolder.balance)
});
and("the machine contains '1000' dollars", () => {
atm.addCash(stepContext.values[0]);
});
when("the Account Holder requests '20' dollars", () => {
cashReceived = atm.withDraw(scenarioContext.given.tableAsEntity.account, stepContext.values[0]);
});
then("the ATM should dispense '20' dollars", () => {
cashReceived.should.be.equal(stepContext.values[0]);
});
and("the account balance should be '80' dollars", () => {
atm.getBalance(scenarioContext.given.tableAsEntity.account).should.be.equal(stepContext.values[0]);
});
});
});