Skip to content

Commit

Permalink
docs(testing): Add custom test example (denoland#9791)
Browse files Browse the repository at this point in the history
  • Loading branch information
getspooky committed Mar 15, 2021
1 parent b2a1ad0 commit 0ae079f
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/testing/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,33 @@ Deno.test("Test Assert Equal Fail Custom Message", () => {
assertEquals(1, 2, "Values Don't Match!");
});
```

### Custom Tests

While Deno comes with powerful
[assertions modules](https://deno.land/std@$STD_VERSION/testing/asserts.ts) but
there is always something specific to the project you can add. Creating
`custom assertion function` can improve readability and reduce the amount of
code.

```js
function assertPowerOf(actual: number, expected: number, msg?: string): void {
let received = actual;
while (received % expected === 0) received = received / expected;
if (received !== 1) {
if (!msg) {
msg = `actual: "${actual}" expected to be a power of : "${expected}"`;
}
throw new AssertionError(msg);
}
}
```

Use this matcher in your code like this:

```js
Deno.test("Test Assert PowerOf", () => {
assertPowerOf(8, 2);
assertPowerOf(11, 4);
});
```

0 comments on commit 0ae079f

Please sign in to comment.