File: mock-es6-class.md

package info (click to toggle)
node-ts-jest 29.1.1%2B~cs0.2.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,408 kB
  • sloc: javascript: 2,573; makefile: 19
file content (75 lines) | stat: -rw-r--r-- 1,657 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
---
id: mock-es6-class
title: Mock ES6 class
---

TypeScript is transpiling your ts file and your module is likely being imported using ES2015s import.
`const soundPlayer = require('./sound-player')`. Therefore creating an instance of the class that was exported as
a default will look like this: `new soundPlayer.default()`. However if you are mocking the class as suggested by the documentation.

```js tab
jest.mock('./sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile }
  })
})
```

```ts tab
jest.mock('./sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return { playSoundFile: mockPlaySoundFile }
  })
})
```

You will get the error

```
TypeError: sound_player_1.default is not a constructor
```

because `soundPlayer.default` does not point to a function. Your mock has to return an object which has a property default
that points to a function.

```js tab
jest.mock('./sound-player', () => {
  return {
    default: jest.fn().mockImplementation(() => {
      return {
        playSoundFile: mockPlaySoundFile,
      }
    }),
  }
})
```

```ts tab
jest.mock('./sound-player', () => {
  return {
    default: jest.fn().mockImplementation(() => {
      return {
        playSoundFile: mockPlaySoundFile,
      }
    }),
  }
})
```

For named imports, like `import { OAuth2 } from './oauth'`, replace `default` with imported module name, `OAuth2` in this example:

```js tab
jest.mock('./oauth', () => {
    return {
        OAuth2: ... // mock here
    }
})
```

```ts tab
jest.mock('./oauth', () => {
    return {
        OAuth2: ... // mock here
    }
})
```