File tree Expand file tree Collapse file tree 2 files changed +97
-0
lines changed Expand file tree Collapse file tree 2 files changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ # TypeScript
2+
3+ Mocha works well with TypeScript. Here's how to get started:
4+
5+ ## Quick Setup
6+
7+ Install dependencies:
8+ ``` bash
9+ npm install --save-dev mocha typescript ts-node @types/mocha @types/node
10+ ```
11+
12+ Run tests:
13+ ``` bash
14+ npx mocha --require ts-node/register " test/**/*.test.ts"
15+ ```
16+
17+ ## Configuration Files
18+
19+ ### package.json
20+ Add a test script:
21+ ``` json
22+ {
23+ "scripts" : {
24+ "test" : " mocha --require ts-node/register 'test/**/*.test.ts'"
25+ }
26+ }
27+ ```
28+
29+ ### tsconfig.json
30+ Basic configuration:
31+ ``` json
32+ {
33+ "compilerOptions" : {
34+ "target" : " es2018" ,
35+ "module" : " commonjs" ,
36+ "strict" : true ,
37+ "esModuleInterop" : true ,
38+ "types" : [" mocha" , " node" ]
39+ }
40+ }
41+ ```
42+
43+ ## Example Test
44+
45+ ``` typescript
46+ // test/math.test.ts
47+ describe (' math functions' , function () {
48+ it (' should add numbers' , function () {
49+ const result = 2 + 2 ;
50+ if (result !== 4 ) {
51+ throw new Error (' Addition failed' );
52+ }
53+ });
54+
55+ it (' should handle async' , async function () {
56+ const result = await Promise .resolve (42 );
57+ if (result !== 42 ) {
58+ throw new Error (' Async test failed' );
59+ }
60+ });
61+ });
62+ ```
63+
64+ ## Common Issues
65+
66+ ** "Cannot find module" errors** : Make sure @types/mocha and @types/node are installed.
67+
68+ ** Compilation errors** : Check that tsconfig.json includes test files and has "types": [ "mocha"] .
69+
70+ ** Import errors** : Use import syntax, not require() in TypeScript files.
71+
72+ ## .mocharc.json (Optional)
73+
74+ For persistent configuration:
75+ ``` json
76+ {
77+ "require" : [" ts-node/register" ],
78+ "spec" : [" test/**/*.test.ts" ]
79+ }
80+ ```
Original file line number Diff line number Diff line change 1+ // Simple TypeScript test example for Mocha
2+ describe ( 'TypeScript Example' , function ( ) {
3+ it ( 'should run TypeScript tests' , function ( ) {
4+ const message : string = 'Hello TypeScript!' ;
5+ if ( message . length === 0 ) {
6+ throw new Error ( 'Message should not be empty' ) ;
7+ }
8+ } ) ;
9+
10+ it ( 'should handle async operations' , async function ( ) {
11+ const delay = ( ms : number ) : Promise < void > =>
12+ new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
13+
14+ await delay ( 1 ) ;
15+ // Test passes if we reach here
16+ } ) ;
17+ } ) ;
You can’t perform that action at this time.
0 commit comments