Skip to content

Commit 0ae079f

Browse files
authored
docs(testing): Add custom test example (denoland#9791)
1 parent b2a1ad0 commit 0ae079f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

docs/testing/assertions.md

+30
Original file line numberDiff line numberDiff line change
@@ -231,3 +231,33 @@ Deno.test("Test Assert Equal Fail Custom Message", () => {
231231
assertEquals(1, 2, "Values Don't Match!");
232232
});
233233
```
234+
235+
### Custom Tests
236+
237+
While Deno comes with powerful
238+
[assertions modules](https://deno.land/std@$STD_VERSION/testing/asserts.ts) but
239+
there is always something specific to the project you can add. Creating
240+
`custom assertion function` can improve readability and reduce the amount of
241+
code.
242+
243+
```js
244+
function assertPowerOf(actual: number, expected: number, msg?: string): void {
245+
let received = actual;
246+
while (received % expected === 0) received = received / expected;
247+
if (received !== 1) {
248+
if (!msg) {
249+
msg = `actual: "${actual}" expected to be a power of : "${expected}"`;
250+
}
251+
throw new AssertionError(msg);
252+
}
253+
}
254+
```
255+
256+
Use this matcher in your code like this:
257+
258+
```js
259+
Deno.test("Test Assert PowerOf", () => {
260+
assertPowerOf(8, 2);
261+
assertPowerOf(11, 4);
262+
});
263+
```

0 commit comments

Comments
 (0)