or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-mock-require

Simple, intuitive mocking of Node.js modules for testing purposes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/mock-require@3.0.x

To install, run

npx @tessl/cli install tessl/npm-mock-require@3.0.0

0

# Mock Require

1

2

Mock Require provides simple, intuitive mocking of Node.js modules for testing purposes. It allows you to replace any required module (local files, external modules, or built-in modules) with custom implementations, making it ideal for unit testing and test isolation.

3

4

## Package Information

5

6

- **Package Name**: mock-require

7

- **Package Type**: npm

8

- **Language**: JavaScript (CommonJS)

9

- **Installation**: `npm install mock-require`

10

11

## Core Imports

12

13

```javascript

14

const mock = require('mock-require');

15

```

16

17

## Basic Usage

18

19

```javascript

20

const mock = require('mock-require');

21

22

// Mock a module with a custom implementation

23

mock('fs', {

24

readFileSync: function() {

25

return 'mocked content';

26

}

27

});

28

29

// Use the mocked module

30

const fs = require('fs');

31

console.log(fs.readFileSync()); // 'mocked content'

32

33

// Stop mocking when done

34

mock.stop('fs');

35

```

36

37

## Capabilities

38

39

### Mock Module

40

41

Replace any module with a custom implementation or redirect to another module.

42

43

```javascript { .api }

44

/**

45

* Mock a module with custom implementation or redirect to another module

46

* @param {string} path - Module path to mock (same as require() path)

47

* @param {*} mockExport - Mock implementation (any value) or path to replacement module (string)

48

*/

49

function mock(path, mockExport);

50

```

51

52

**Usage Examples:**

53

54

```javascript

55

const mock = require('mock-require');

56

57

// Mock with custom object

58

mock('http', {

59

request: function() {

60

console.log('http.request called');

61

}

62

});

63

64

// Mock with custom function

65

mock('./utils', function() {

66

return 'mocked utility';

67

});

68

69

// Redirect one module to another

70

mock('fs', 'path'); // require('fs') will return require('path')

71

72

// Mock non-existent modules

73

mock('fake-module', { fake: true });

74

```

75

76

**Supported Mock Types:**

77

- **Objects**: Custom object implementations

78

- **Functions**: Function replacements

79

- **Strings**: Path to another module to use as replacement

80

- **Any Value**: Primitives, arrays, null, undefined, or any JavaScript value

81

82

### Stop Mocking

83

84

Remove the mock for a specific module, restoring its original behavior.

85

86

```javascript { .api }

87

/**

88

* Stop mocking a specific module

89

* @param {string} path - Module path to stop mocking

90

*/

91

mock.stop(path);

92

```

93

94

**Usage Example:**

95

96

```javascript

97

const mock = require('mock-require');

98

99

mock('./module', { mocked: true });

100

const mockVersion = require('./module');

101

102

mock.stop('./module');

103

const realVersion = require('./module');

104

105

// mockVersion !== realVersion

106

```

107

108

### Stop All Mocking

109

110

Remove all registered mocks without the need to stop them individually.

111

112

```javascript { .api }

113

/**

114

* Remove all registered mocks

115

*/

116

mock.stopAll();

117

```

118

119

**Usage Example:**

120

121

```javascript

122

const mock = require('mock-require');

123

124

mock('fs', {});

125

mock('path', {});

126

mock('http', {});

127

128

// Clean up all mocks at once

129

mock.stopAll();

130

```

131

132

### Re-require Module

133

134

Clear Node.js require cache for a module and require it again, useful for applying mocks to already-cached modules.

135

136

```javascript { .api }

137

/**

138

* Clear require cache and re-require a module

139

* @param {string} path - Module path to refresh from cache

140

* @returns {*} The freshly required module

141

*/

142

mock.reRequire(path);

143

```

144

145

**Usage Example:**

146

147

```javascript

148

const mock = require('mock-require');

149

150

// Module is already cached

151

const fs = require('fs');

152

const fileToTest = require('./fileToTest');

153

154

// Apply mock after initial require

155

mock('fs', { mocked: true });

156

157

// Re-require to apply the mock

158

const updatedFileToTest = mock.reRequire('./fileToTest');

159

// updatedFileToTest now uses the mocked fs

160

```

161

162

## Advanced Features

163

164

### Path Resolution

165

166

Mock Require intelligently handles different types of module paths:

167

168

- **Local modules**: `./file.js`, `../utils/helper.js` - Resolved relative to the calling file

169

- **External modules**: `lodash`, `express` - Resolved from node_modules

170

- **Built-in modules**: `fs`, `http`, `path` - Node.js core modules

171

- **Node path modules**: Modules in NODE_PATH environment variable

172

- **Non-existent modules**: Modules that don't exist in the filesystem can still be mocked

173

174

**Path Resolution Behavior:**

175

- Paths are normalized using `normalize-path` for cross-platform compatibility

176

- Local modules are resolved relative to the file calling `mock()`, not the current working directory

177

- External and built-in modules are resolved using Node's standard resolution algorithm

178

- Non-existent local modules can be mocked and will be resolved to their expected path

179

180

### Cascade Mocking

181

182

Mocks can depend on other mocks, creating a cascade effect:

183

184

```javascript

185

mock('path', { mocked: true });

186

mock('fs', 'path'); // fs will use the mocked path

187

const fs = require('fs'); // Returns { mocked: true }

188

```

189

190

### Error Handling

191

192

Mock Require handles various error scenarios gracefully:

193

194

**Module Not Found:**

195

When you stop mocking a non-existent module, subsequent require attempts will throw the standard `MODULE_NOT_FOUND` error:

196

197

```javascript

198

mock('non-existent-module', { fake: true });

199

mock.stop('non-existent-module');

200

201

try {

202

require('non-existent-module');

203

} catch (e) {

204

console.log(e.code); // 'MODULE_NOT_FOUND'

205

}

206

```

207

208

### Test Isolation

209

210

Perfect for test scenarios where you need to isolate dependencies:

211

212

```javascript

213

// In test setup

214

afterEach(() => {

215

mock.stopAll(); // Clean up all mocks between tests

216

});

217

218

it('should handle file operations', () => {

219

mock('fs', {

220

readFileSync: () => 'test content',

221

writeFileSync: () => {}

222

});

223

224

// Test code that uses fs

225

const result = myFunction();

226

assert.equal(result, 'expected');

227

});

228

```