UNPKG

2.52 kBMarkdownView Raw
1#mock-require
2
3####Simple, intuitive mocking of Node.js modules.
4
5[![Build Status](https://travis-ci.org/boblauer/mock-require.svg)](https://travis-ci.org/boblauer/mock-require)
6
7##About
8
9mock-require is useful if you want to mock `require` statements in Node.js. I wrote it because I wanted something with a straight-forward API that would let me mock anything, from a single exported function to a standard library.
10
11##Usage
12
13```javascript
14var mock = require('mock-require');
15
16mock('http', { request: function() {
17 console.log('http.request called');
18}});
19
20var http = require('http');
21http.request(); // 'http.request called'
22```
23##API
24```javascript
25mock(path, mockExport)
26```
27
28__path__: `String`
29
30The module you that you want to mock. This is the same string you would pass in if you wanted to `require` the module.
31
32This path should be relative to the current file, just as it would be if you were to `require` the module from the current file. mock-require is smart enough to mock this module everywhere it is required, even if it's required from a different file using a different relative path.
33
34__mockExport__ : `object/function`
35
36The function or object you want to be returned from `require`, instead of the `path` module's exports.
37
38__mockExport__ : `string`
39
40The module you want to be returned from `require`, instead of the `path` module's export. This allows you to replace modules with other modules. For example, if you wanted to replace the `fs` module with the `path` module (you probably wouldn't, but if you did):
41
42```javascript
43require('fs', 'path');
44require('fs') === require('path'); // true
45```
46This is useful if you have a mock library that you want to use in multiple places. For example:
47
48`test/spy.js`:
49```javascript
50module.exports = function() {
51 return 'this was mocked';
52};
53```
54
55`test/a_spec.js`:
56```javascript
57var mock = require('mock-require');
58mock('../some/dependency', './spy');
59...
60```
61
62`test/b_spec.js`:
63```javascript
64var mock = require('mock-require');
65mock('../some/other/dependency', './spy');
66...
67```
68---
69```javascript
70mock.stop(path)
71```
72__path__: `String`
73
74The module you that you want to stop mocking. This is the same string you would pass in if you wanted to `require` the module.
75
76This will only modify variables used after `mock.stop` is called. For example:
77
78```javascript
79var mock = require('mock-require');
80mock('fs', { mockedFS: true });
81
82var fs1 = require('fs');
83
84mock.stop('fs');
85
86var fs2 = require('fs');
87
88fs1 === fs2; // false
89```
90
91##Test
92npm test