Skip to content

Commit 7618a71

Browse files
authored
Adding documentation on .js fixture files
(Taking a stab at) adding documentation on `.js` fixture files. Current documentation mentions that `.js` fixture files are possible, but doesn't describe how to use them, leading to issues like cypress-io/cypress#1271 . I do think the current `.js` fixture support should get a good rethink (as mentioned 4 years ago in that issue) , but in the meantime it should have some documentation on how to use it (or fully remove any mention of it from the documentation, making it "unsupported").
1 parent 43bb00b commit 7618a71

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

content/api/commands/fixture.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,47 @@ it('loads the same object', () => {
125125
})
126126
})
127127
```
128+
#### JavaScript file
129+
Cypress allows a `.js` file as a fixture, in places where JSON is expected.
130+
The contents of this file are treated as a something that evaluates to a JavaScript object (within Cypress, the content of the file is `eval()`-ed, with parentheses:
131+
132+
```javascript
133+
let fixtureValue = eval("(" + fileContent + ")");
134+
```
135+
136+
The `.js` file should evaluate to a JavaScript object (see examples below); many things that are valid JavaScript, are not allowed in this file, specifically, the file should _not_ end in a semi-colon (`;`).
137+
138+
Although it is possible to make complex behaviour through this method, note that fixtures are meant to be "a fixed set of data".
139+
If you want dynamic responses, a better solution is to use a [`routeHandler` function](/api/commands/intercept#Using-the-routeHandler-function).
140+
141+
Note that any valid JSON is valid as a `.js` fixture.
142+
The advantage is that that "sloppy" JSON is allowed: use single-quotes (or no quotes for keys), trailing commas, and comments.
143+
144+
<Alert type="danger">
145+
The code in the `.js` fixture gets executed.
146+
If you import your fixtures (or values in your fixtures) from an external source, into fixture files with a `.js` extension, this may be a security problem!
147+
In general, never use `.js` fixtures, unless you 100% control what is in the file.
148+
</Alert>
149+
150+
##### Examples
151+
152+
"Sloppy" JSON `fixture/users.js` with comments
153+
```javascript
154+
[
155+
{
156+
name: 'Bob' + '\u2022', // add a unicode black dot to the name
157+
age: 25,
158+
}
159+
]
160+
```
161+
162+
Generate many Bobs `fixture/users.js`
163+
```javascript
164+
Array(100).fill(0).map((_, index) => ({
165+
name: `Bob_${index}`,
166+
age: 25 + Math.floor(index / 2),
167+
}))
168+
```
128169

129170
### Images
130171

0 commit comments

Comments
 (0)