Skip to content

Commit

Permalink
Merge pull request #2049 from kobbikobb/patch-1
Browse files Browse the repository at this point in the history
Documentation for stubbing modules
  • Loading branch information
fatso83 committed Jun 25, 2019
2 parents e74c582 + 3148eac commit 383f5ca
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
54 changes: 54 additions & 0 deletions docs/_howto/stub-dependency.md
@@ -0,0 +1,54 @@
---
layout: page
title: How to stub a dependency of a module?
---

Sinon is simply a stubbing library, not a module interception library. Stubbing dependencies is highly dependant on your enviroment and the implementation. For Node environments, we usually recommend solutions targetting [link seams](./link-seams-commonjs) or explicit dependency injection. Though in some simple cases, you can get away with just using Sinon by modifying the module exports of the dependency.

To stub a dependency (imported module) of a module under test you have to import it explicitly in your test and stub the desired method. For the stubbing to work, the stubbed method cannot be [destructured](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), neither in the module under test nor in the test.

## Example: dependencyModule.js
```javascript

function getSecretNumber() {
return 44;
}

module.exports = {
getSecretNumber
};
```

## Example: moduleUnderTest.js

```javascript
const dependencyModule = require("./dependencyModule");

function getTheSecret() {
return `The secret was: ${dependencyModule.getSecretNumber()}`;
}

module.exports = {
getTheSecret
};
```

## Example: test.js

```javascript
const assert = require("assert");
const sinon = require("sinon");

const dependencyModule = require("./dependencyModule");
const { getTheSecret } = require("./moduleUnderTest");

describe("moduleUnderTest", function() {
describe("when the secret is 3", function() {
it("should be returned with a string prefix", function() {
sinon.stub(dependencyModule, "getSecretNumber").returns(3);
const result = getTheSecret();
assert.equal(result, "The secret was: 3");
});
});
});
```
2 changes: 2 additions & 0 deletions docs/_releases/latest/stubs.md
Expand Up @@ -76,6 +76,8 @@ Replaces `object.method` with a stub function. An exception is thrown if the pro

The original function can be restored by calling `object.method.restore();` (or `stub.restore();`).

Stubs can be used to replace a module's dependencies, ensuring it is tested in isolation. [For simple cases](../../_howto/stub-dependency.md) you might not need additional helper libraries, but for more complex cases you might need to [target the module loading mechanisms](../../link-seams-commonjs.md).

#### ~~`var stub = sinon.stub(object, "method", func);`~~

This has been removed from `v3.0.0`. Instead you should use
Expand Down

0 comments on commit 383f5ca

Please sign in to comment.