Skip to content
Draft
Show file tree
Hide file tree
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
80 changes: 80 additions & 0 deletions docs/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# TypeScript

Mocha works well with TypeScript. Here's how to get started:

## Quick Setup

Install dependencies:
```bash
npm install --save-dev mocha typescript ts-node @types/mocha @types/node
```

Run tests:
```bash
npx mocha --require ts-node/register "test/**/*.test.ts"
```

## Configuration Files

### package.json
Add a test script:
```json
{
"scripts": {
"test": "mocha --require ts-node/register 'test/**/*.test.ts'"
}
}
```

### tsconfig.json
Basic configuration:
```json
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"types": ["mocha", "node"]
}
}
```

## Example Test

```typescript
// test/math.test.ts
describe('math functions', function() {
it('should add numbers', function() {
const result = 2 + 2;
if (result !== 4) {
throw new Error('Addition failed');
}
});

it('should handle async', async function() {
const result = await Promise.resolve(42);
if (result !== 42) {
throw new Error('Async test failed');
}
});
});
```

## Common Issues

**"Cannot find module" errors**: Make sure @types/mocha and @types/node are installed.

**Compilation errors**: Check that tsconfig.json includes test files and has "types": ["mocha"].

**Import errors**: Use import syntax, not require() in TypeScript files.

## .mocharc.json (Optional)

For persistent configuration:
```json
{
"require": ["ts-node/register"],
"spec": ["test/**/*.test.ts"]
}
```
17 changes: 17 additions & 0 deletions examples/typescript-basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Simple TypeScript test example for Mocha
describe('TypeScript Example', function() {
it('should run TypeScript tests', function() {
const message: string = 'Hello TypeScript!';
if (message.length === 0) {
throw new Error('Message should not be empty');
}
});

it('should handle async operations', async function() {
const delay = (ms: number): Promise<void> =>
new Promise(resolve => setTimeout(resolve, ms));

await delay(1);
// Test passes if we reach here
});
});