Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contributing.md instructions for creating tests #88

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,41 @@ Article PRs should be reviewed using the [PR review process here](https://github

### Creating tests

Test files must be within `/src`, with a file name ending in `.test.<ext>`, where `<ext>` is one of `js` `mjs` `jsx` `ts` `tsx`.
1. For some module `foo.js`, create a file `foo.test.js` in the same directory.

- `.ts` / `.mjs` / `.js` are all valid extensions.
- `.tsx` / `.jsx` are permitted, though unless the XML syntax is necessary, use `.ts` / `.mjs` instead.
- Tests must be within `/src`.

2. Import the module to be tested.

- For TypeScript, Jest utilities are not in global scope, so you will need to import these from `@jest/globals`.

3. Use Jest's [`expect`](https://jestjs.io/docs/expect), [`it`](https://jestjs.io/docs/api#testname-fn-timeout) and [`describe`](https://jestjs.io/docs/api#describename-fn) to organise and assert the behaviour of the module. A test name should start with a verb, and descriptions should be used to indicate what component is being tested.

```ts
/** @file criticalMathModule.test.ts */
import { describe, expect, it } from "@jest/globals"; // only needed for TypeScript
import { isEven, log2 } from "./criticalMathModule";

describe("isEven", () => {
it("checks if numbers are even", () => {
expect(isEven(1)).toBe(false);
expect(isEven(4)).toBe(true);
});
});

describe("log2", () => {
it("returns the base-2 logarithm of a number", () => {
expect(log2(1024)).toBeCloseTo(10);
});

it("throws an error for non-positive numbers", () => {
expect(log2(0)).toThrow();
expect(log2(-1)).toThrow();
Comment on lines +45 to +46
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't catch the throw unless you wrap the code to test in a function:

Suggested change
expect(log2(0)).toThrow();
expect(log2(-1)).toThrow();
expect(() => log2(0)).toThrow();
expect(() => log2(-1)).toThrow();

(I know this is just example code, but still.)

});
});
```

## How to review a code change

Expand Down