mocha-cakes-2
mocha-cakes-2 copied to clipboard
When Each
Is it possible to provide a When
step that is executed by multiple scenarios, without duplicating the When call each time.
For example, we have many tests like this:
var unauthorizedScenarios =
[
{
description: "No Authorization Header",
givenDescription: "no authorization header is provided",
authHeader: null
},
{
description: "Invalid Authorization Header",
givenDescription: "an authorization header is provided in an incorrect format",
authHeader: "im-a-key"
}
];
unauthorizedScenarios.forEach(scenario => Scenario(scenario.description, function () {
Given(scenario.givenDescription, function () {
authHeader = scenario.authHeader
});
When("making an API request that requires authorization", async function () {
response = await request(config.baseUrl)
.get("payments/pay_y3oqhf46pyzuxjbcn2giaqnb44")
.set("Authorization", authHeader);
});
Then("it returns HTTP status code 401 (Unauthorized)", function () {
response.status.should.equal(401);
});
}));
What I don't like about this approach is the separation between the scenarios and the tests and it only works in cases where we have the same assertions.
What I would prefer to do is something like:
WhenEach("Doing something every time", function() {
});
ThenEach("Assert on every scenario in the feature", function() {
});
Scenario("Scenario 1", function() {
Given("Some context", function() {
});
Then("Scenario specific assertion", function() {
});
});
Essentially a WhenEach
, GivenEach
and ThenEach
would run on every scenario. I'm happy to send a PR for this if you can guide me on how best to hook into the scenarios.
This project seems to have basic gherkin support ie Feature/Scenario/GWT etc. Seems you're looking for more advanced features such as ScenarioOutlines (ie no more foreach) and Backgrounds which get executed before each Scenario. You may want to checkout my project (sorry for the plug - but I think it will serve your needs better), as it supports the full Gherkin syntax plus a bunch of other advanced features. I recommend using the latest @beta version which was just released. Let me know if you have any questions. https://github.com/dotnetprofessional/LiveDoc/tree/master/packages/livedoc-mocha
@dotnetprofessional I had a look but can't see an example of how you're repeating your when
on each scenario.
I'm used to defining a shared "act" or "when" and then just switching the context within the scenario as it avoids a lot of duplication.
Probably shouldn't have an extended chat on here, please open an issue on my project site. However, to quickly answer your question see: https://github.com/dotnetprofessional/LiveDoc/blob/master/packages/livedoc-mocha/docs/API.md#scenario-outline
This uses Scenario Outlines which is part of the Gherkin spec. Feel free to open an issue on the project if you need more details.