我认为 jasmine 只是一个 TDD 框架,而不是 BDD,因为它没有 BDD 框架所具有的两层抽象:
- 我们该怎么办? (通常在 txt 文件中)
- 我们如何做到这一点? (javascript 中的可重用实现)
不过没关系,这是一个很好的起点。我也不喜欢重新发明轮子(使用基于 txt 的语言)。我找到了一个基于 jasmine 的 BDD 框架,对我来说这是完美的解决方案:https://github.com/DealerDotCom/karma-jasmine-cucumber
例如:
specs.js(我们所做的)
feature('Calculator: add')
.scenario('should be able to add 2 numbers together')
.when('I enter "1"')
.and('I add "2"')
.then('I should get "3"')
.scenario('should be able to add to a result of a previous addition')
.given('I added "1" and "2"')
.when('I add "3"')
.then('I should get "6"')
steps.js(我们是怎么做的)
featureSteps('Calculator:')
.before(function(){
this.values = [];
this.total = null;
})
.given('I added "(.*)" and "(.*)"', function(first, second){
this.when('I enter "' + first + '"');
this.when('I add "' + second + '"');
})
.when('I enter "(.*)"', function(val){
this.values.push(val * 1);
})
.when('I add "(.*)"', function(val){
this.values.push(val * 1);
this.total = this.values[0] + this.values[1];
this.values = [this.total];
})
.then('I should get "(.*)"', function(val){
expect(this.total).toBe(val * 1);
})
2016 年 2 月 16 日更新:
经过几个月的 BDD 实践,我最终获得了基于 txt 的功能描述和 ofc。配小黄瓜。我认为最好在特性描述中写一些非常高抽象级别的东西,而不是我之前在我的 karma-jasmine-cucumber 示例中写的东西。通过我的旧示例,我现在宁愿写这样的东西:
Scenario: Addition of numbers
Given I have multiple numbers
When I add these numbers together
Then I should get their sum as result
这就是我目前喜欢的方式。我使用让步骤定义来设置固定装置和断言的值,但是 ofc。如果你愿意,你可以给Examples 和gherkin:
Scenario: Addition of numbers
Given I have <multiple numbers>
When I add these numbers together
Then I should get <their sum> as result
Examples:
| multiple numbers | their sum |
| 1, 2, 3, 6 | 12 |
| 8, 5 | 13 |
| 5, -10, 32 | 27 |
Cucumber 将这 3 行翻译成 3 个场景,例如:
Given I have 1, 2, 3, 6
When I add these numbers together
Then I should get 12 as result
也许调试起来稍微容易一些,但是您必须为这些值编写解析器,例如拆分“1、2、3、6”字符串并解析值以获取数字数组。我认为您可以决定哪种方式更适合您。
高抽象级别的功能描述真正有趣的是,您可以编写多个不同的步骤定义。因此,例如,您可以测试 2 个不同的 api,它们做同样的事情,或者坚持使用计算器示例,您可以为多个用户界面(cli、web 应用程序等)编写 e2e 测试,或者您可以编写一个简单的测试,它仅测试域。无论如何,功能描述或多或少是可重复使用的。
2016 年 4 月 15 日更新:
我决定使用Yadda 和mocha 而不是Cucumber 和jasmine。我也喜欢 Cucumber 和 jasmine,但我认为 Yadda 和 mocha 更灵活。