Skip to content

Commit f8c20e5

Browse files
fatso83mroderick
andauthored
New article: making Sinon work with complex setups (#2540)
Co-authored-by: Morgan Roderick <[email protected]>
1 parent cb5b962 commit f8c20e5

File tree

9 files changed

+294
-897
lines changed

9 files changed

+294
-897
lines changed

docs/CONTRIBUTING.md

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ When you're contributing documentation changes for code in `main` branch, then d
99
If you're contributing documentation for an existing release, then your documentation changes should go into the documentation for that release in `_releases/` folder, and possibly several of the following releases also.
1010

1111
### Where are all the _releases_?
12+
1213
All the files that used to be under `_releases` in the `main` can be found in the `releases` branch. The `main` branch now only keeps the latest version. That means, to fix the docs of published releases you need to checkout the _relases branch_ and supply a PR against that.
1314

1415
## Running the documentation site locally

docs/_howto/link-seams-commonjs.md

+11-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
---
22
layout: page
3-
title: How to use Link Seams with CommonJS
3+
title: How to stub out CommonJS modules
44
---
55

6-
This page describes how to isolate your system under test, by stubbing out dependencies with [link seams][seams].
6+
This page describes how to isolate your system under test, by targetting the [link seams][seams]; replacing your dependencies with stubs you control.
77

8-
This is the CommonJS version, so we will be using [proxyquire][proxyquire] to construct our seams.
8+
> If you want a better understand of the example and get a good description of what _seams_ are, we recommend that you read the [seams (all 3 web pages)][seams] excerpt from the classic [Working Effectively with Legacy Code][legacy], though it is not strictly necessary.
99
10-
To better understand the example and get a good description of what seams are, we recommend that you read the [seams (all 3 web pages)][seams] excerpt from [Working Effectively with Legacy Code][legacy] before proceeding.
10+
This guide targets the CommonJS module system, made popular by NodeJS. There are other module systems, but until recent years this was the de-facto module system and even when the actual EcmaScript Module standard arrived in 2015, transpilers and bundlers can still _output_ code as CJS modules. For instance, Typescript outputs CJS modules per default as of 2023, so it is still relevant, as your `import foo from './foo'` might still end up being transpiled into `const foo = require('./foo')` in the end.
11+
12+
<!-- TODO: input link to the other article on stubbing ESM -->
13+
14+
## Hooking into `require`
15+
16+
For us to replace the underlying calls done by `require` we need a tool to hook into the process. There are many tools that can do this: rewire, proxyquire, [Quibble][quibble], etc. This example will be using [proxyquire][proxyquire] to construct our _seams_ (i.e. replace the modules), but the actual mechanics will be very similar for the other tools.
1117

1218
Read it?
1319

@@ -83,3 +89,4 @@ describe("example", function () {
8389
[proxyquire]: https://github.com/thlorenz/proxyquire
8490
[demo-proxyquire]: https://github.com/sinonjs/demo-proxyquire
8591
[legacy]: https://www.goodreads.com/book/show/44919.Working_Effectively_with_Legacy_Code
92+
[quibble]: https://www.npmjs.com/package/quibble

docs/_howto/typescript-swc.md

+264
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
---
2+
layout: page
3+
title: "Case study: real world dependency stubbing"
4+
---
5+
6+
Sinon is a simple tool that only tries to do a few things and do them well: creating and injecting test doubles (spies, fakes, stubs) into objects. Unfortunately, in todays world of build pipelines, complex tooling, transpilers and different module systems, doing the simple thing quickly becomes difficult.
7+
8+
This article is a detailed step-by-step guide on how one can approach the typical issues that arise and various approaches for debugging and solving them. The real-world case chosen is using Sinon along with [SWC][swc-project], running tests written in TypeScript in the [Mocha test runner][mocha] and wanting to replace dependencies in this ([SUT][sut]). The essence is that there are always _many_ approaches for achieving what you want. Some require tooling, some can get away with almost no tooling, some are general in nature (not specific to SWC for instance) and some are a blend. This means you can usually make some of these approaches work for other combinations of tooling as well, once you understand what is going on. Draw inspiration from the approach and figure out what works for you!
9+
10+
## On Typescript
11+
12+
The Sinon project does not explicitly list TypeScript as a supported target environment. That does not mean Sinon will not run, just that there are so many complications that we cannot come up with guides on figuring out the details for you on every system :)
13+
14+
Typescript is a super-set of EcmaScript (JavaScript) and can be transpiled in a wide variety of ways into EcmaScript, both by targetting different runtimes (ES5, ES2015, ES2023, etc) and module systems (CommonJS, ESM, AMD, ...). Some transpiler are closer to the what the standard TypeScript compiler produces, some are laxer in various ways and additionally they have all kinds of options to tweak the result. This is indeed complex, so before you dig yourself done in this matter, it is essential that you try to figure out what the resulting code _actually_ looks like.
15+
16+
As you will see in this guide, adding a few sprinkles of `console.log` with the output of [`Object.getOwnPropertyDescriptor(object, propname)`][get-own] is usually sufficient to understand what is going on!
17+
18+
All code and working setups described in this guide are on [Github][master-branch] and links to the correct branch can be found in each section.
19+
20+
## Scenario
21+
22+
### Tech
23+
24+
- Mocha: drives the tests
25+
- SWC: very fast Rust-based transpiler able to target different module systems (CJS, ESM, ...) and target runtimes (ES5, ES2020, ...)
26+
- Typescript: Type-safe EcmaScript superset
27+
- Sinon: library for creating and injecting test doubles (stubs, mocks, spies and fakes)
28+
- Module system: CommonJS
29+
30+
### Desired outcome
31+
32+
Being able to replace exports on the dependency `./other` with a Sinon created test double in `main.ts` when running tests (see code below).
33+
34+
### Problem
35+
36+
Running tests with `ts-node` works fine, but changing the setup to using SWC instead results in the tests failing with the following output from Mocha:
37+
38+
```
39+
1) main
40+
should mock:
41+
TypeError: Descriptor for property toBeMocked is non-configurable and non-writable
42+
```
43+
44+
### Original code
45+
46+
**main.ts**
47+
48+
```typescript
49+
import { toBeMocked } from "./other";
50+
51+
export function main() {
52+
const out = toBeMocked();
53+
console.log(out);
54+
}
55+
```
56+
57+
**other.ts**
58+
59+
```typescript
60+
export function toBeMocked() {
61+
return "I am the original function";
62+
}
63+
```
64+
65+
**main.spec.ts**
66+
67+
```typescript
68+
import sinon from "sinon";
69+
import "./init";
70+
import * as Other from "./other";
71+
import { main } from "./main";
72+
import { expect } from "chai";
73+
74+
const sandbox = sinon.createSandbox();
75+
76+
describe("main", () => {
77+
let mocked;
78+
it("should mock", () => {
79+
mocked = sandbox.stub(Other, "toBeMocked").returns("mocked");
80+
main();
81+
expect(mocked.called).to.be.true;
82+
});
83+
});
84+
```
85+
86+
Additionally, both the `.swcrc` file used by SWC and the `tsconfig.json` file used by `ts-node` is configured to produce modules of the CommonJS form, not ES Modules.
87+
88+
### Brief Analysis
89+
90+
The error message indicates the resulting output of transpilation is different from that of `ts-node`, as this is Sinon telling us that it is unable to do anything with the property of an object, when the [property descriptor][descriptor] is essentially immutable.
91+
92+
Let us sprinkle some debugging statements to figure out what the differences between the two tools are. First we will add these some debugging output to the beginning of the test, for instance just after `it("should mock", () => {`, to see what the state is _before_ we attempt to do any modifications:
93+
94+
```javascript
95+
console.log("Other", Other);
96+
console.log(
97+
"Other property descriptors",
98+
Object.getOwnPropertyDescriptors(Other)
99+
);
100+
```
101+
102+
Now let's try what happens when running this again, once with the existing SWC setup and a second time after changing the config file for Mocha, `.mocharc.json`, to use `'ts-node'` instead of `'@swc/register` in its `'require'` array. This `--require` option of Node is for modules that will be run by Node before _your_ code, making it possible to do stuff like hook into `require` and transpile code on-the-fly.
103+
104+
#### Output of a SWC configured run of `npm test`
105+
106+
```
107+
Other { toBeMocked: [Getter] }
108+
Other property descriptors {
109+
__esModule: {
110+
value: true,
111+
writable: false,
112+
enumerable: false,
113+
configurable: false
114+
},
115+
toBeMocked: {
116+
get: [Function: get],
117+
set: undefined,
118+
enumerable: true,
119+
configurable: false
120+
}
121+
}
122+
1) should mock
123+
124+
125+
0 passing (4ms)
126+
1 failing
127+
128+
1) main
129+
should mock:
130+
TypeError: Descriptor for property toBeMocked is non-configurable and non-writable
131+
```
132+
133+
#### Output of a `ts-node` configured run of `npm test`
134+
135+
```
136+
Other { toBeMocked: [Function: toBeMocked] }
137+
Other property descriptors {
138+
__esModule: {
139+
value: true,
140+
writable: false,
141+
enumerable: false,
142+
configurable: false
143+
},
144+
toBeMocked: {
145+
value: [Function: toBeMocked],
146+
writable: true,
147+
enumerable: true,
148+
configurable: true
149+
}
150+
}
151+
mocked
152+
✔ should mock
153+
```
154+
155+
The important difference to note about the object `Other` is that the property `toBeMocked` is a simple writable _value_ in the case of `ts-node` and a non-configurable _getter_ in the case of SWC. It being a getter is not a problem for Sinon, as we have a multitude of options for replacing those, but if `configurable` is set to `false` Sinon cannot really do anything about it.
156+
157+
Let us take a closer look.
158+
159+
#### Conclusion of analysis
160+
161+
SWC transforms the imports on the form `import * as Other from './other'` into objects where the individual exports are exposed through immutable accessors (_getters_).
162+
163+
We can address this issue in mainly 3 ways:
164+
165+
1. somehow reconfigure SWC to produce different output when running tests that we can work with, either making writable values or configurable getters
166+
2. use pure dependency injection, opening up `./other.ts` to be changed from the inside
167+
3. address how modules are loaded, injecting [an additional `require` "hook"](https://levelup.gitconnected.com/how-to-add-hooks-to-node-js-require-function-dee7acd12698)
168+
169+
# Solutions
170+
171+
## Mutating the output from the transpiler
172+
173+
> [Working code][swc-mutable-export]
174+
175+
If we can just flip the `configurable` flag to `true` during transpilation, Sinon could be instructed to replace the getter. It turns out, there is a SWC _plugin_ that does just that: [swc_mut_cjs_exports](https://www.npmjs.com/package/swc_mut_cjs_exports). By installing that and adding the following under the `jsc` key in `.swcrc`, you know get a configurable property descriptor.
176+
177+
```json
178+
"experimental": {
179+
"plugins": [[ "swc_mut_cjs_exports", {} ]]
180+
},
181+
```
182+
183+
A getter _is_ different from a value, so you need to change your testcode slightly to replace the getter:
184+
185+
```js
186+
const stub = sandbox.fake.returns("mocked");
187+
sandbox.replaceGetter(Other, "toBeMocked", () => stub);
188+
```
189+
190+
## Use pure dependency injection
191+
192+
> [Working code][pure-di]
193+
194+
This technique works regardless of language, module systems, bundlers and tool chains, but requires slight modifications of the SUT to allow modifying it. Sinon cannot help with resetting state automatically in this scenario.
195+
196+
**other.ts**
197+
198+
```typescript
199+
function _toBeMocked() {
200+
return "I am the original function";
201+
}
202+
203+
export let toBeMocked = _toBeMocked;
204+
205+
export function _setToBeMocked(mockImplementation) {
206+
toBeMocked = mockImplementation;
207+
}
208+
```
209+
210+
**main.spec.ts**
211+
212+
```typescript
213+
describe("main", () => {
214+
let mocked;
215+
let original = Other.toBeMocked;
216+
217+
after(() => Other._setToBeMocked(original))
218+
219+
it("should mock", () => {
220+
mocked = sandbox.stub().returns("mocked");
221+
Other._setToBeMocked(mocked)
222+
main();
223+
expect(mocked.called).to.be.true;
224+
});
225+
```
226+
227+
## Hooking into Node's module loading
228+
229+
> [Working code][cjs-mocking]
230+
231+
This is what [the article on _targetting the link seams_][link-seams-cjs] is about. The only difference here is using Quibble instead of Proxyquire. Quibble is slightly terser and also supports being used as a ESM _loader_, making it a bit more modern and useful. The end result:
232+
233+
```typescript
234+
describe("main module", () => {
235+
let mocked, main;
236+
237+
before(() => {
238+
mocked = sandbox.stub().returns("mocked");
239+
quibble("./other", { toBeMocked: mocked });
240+
({ main } = require("./main"));
241+
});
242+
243+
it("should mock", () => {
244+
main();
245+
expect(mocked.called).to.be.true;
246+
});
247+
});
248+
```
249+
250+
# Final remarks
251+
252+
As can be seen, there are lots of different paths to walk in order to achieve the same basic goal. Find the one that works for your case.
253+
254+
[link-seams-cjs]: /how-to/link-seams-commonjs/
255+
[master-branch]: https://github.com/fatso83/sinon-swc-bug
256+
[descriptor]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
257+
[get-own]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor
258+
[swc-project]: https://swc.rs/
259+
[mocha]: https://mochajs.org/
260+
[sut]: http://xunitpatterns.com/SUT.html
261+
[require-hook]: https://levelup.gitconnected.com/how-to-add-hooks-to-node-js-require-function-dee7acd12698
262+
[swc-mutable-export]: https://github.com/fatso83/sinon-swc-bug/tree/swc-with-mutable-exports
263+
[pure-di]: https://github.com/fatso83/sinon-swc-bug/tree/pure-di
264+
[cjs-mocking]: https://github.com/fatso83/sinon-swc-bug/tree/cjs-mocking

docs/_includes/header.html

-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
<ul class="nav navbar-nav navbar-right">
1010
<li><a href="{{ site.baseurl }}/releases/v{{site.sinon.current_major_version}}">Documentation</a></li>
1111
<li><a href="{{ site.baseurl }}/releases/">Releases</a></li>
12-
<li><a href="{{ site.baseurl }}/guides/">Guides</a></li>
1312
<li><a href="{{ site.baseurl }}/how-to/">How To</a></li>
1413
<li><a href="https://github.com/sinonjs/" target="blank" class="github-nav"><img src="{{ "/assets/images/github.png" | prepend: site.baseurl }}" alt="Github"></a></li>
1514
</ul>

0 commit comments

Comments
 (0)