Skip to content

Commit 05beb8d

Browse files
authored
Create solution.md
1 parent d59d902 commit 05beb8d

File tree

1 file changed

+50
-0
lines changed
  • 1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
The test demonstrates one of the temptations a developer meets when writing tests.
2+
3+
What we have here is actually 3 tests, but layed out as a single function with 3 asserts.
4+
5+
Sometimes it's easier to write this way, but if an error occurs, it's much less obvious what went wrong.
6+
7+
If an error happens in the middle of a complex execution flow, then we'll have to figure out the data at that point. We'll actually have to *debug the test*.
8+
9+
It would be much better to break the test into multiple `it` blocks with clearly written inputs and outputs.
10+
11+
Like this:
12+
```js
13+
describe("Raises x to power n", function() {
14+
it("5 in the power of 1 equals 5", function() {
15+
assert.equal(pow(5, 1), 5);
16+
});
17+
18+
it("5 in the power of 2 equals 25", function() {
19+
assert.equal(pow(5, 2), 25);
20+
});
21+
22+
it("5 in the power of 3 equals 125", function() {
23+
assert.equal(pow(5, 3), 125);
24+
});
25+
});
26+
```
27+
28+
We replaced the single `it` with `describe` and a group of `it` blocks. Now if something fails we would see clearly what the data was.
29+
30+
Also we can isolate a single test and run it in standalone mode by writing `it.only` instead of `it`:
31+
32+
33+
```js
34+
describe("Raises x to power n", function() {
35+
it("5 in the power of 1 equals 5", function() {
36+
assert.equal(pow(5, 1), 5);
37+
});
38+
39+
*!*
40+
// Mocha will run only this block
41+
it.only("5 in the power of 2 equals 25", function() {
42+
assert.equal(pow(5, 2), 25);
43+
});
44+
*/!*
45+
46+
it("5 in the power of 3 equals 125", function() {
47+
assert.equal(pow(5, 3), 125);
48+
});
49+
});
50+
```

0 commit comments

Comments
 (0)