Skip to content

Commit f34599e

Browse files
author
Adrian Bienias
authored
docs: Describe random string case in snapshot testing (#12501)
1 parent b0dc2e4 commit f34599e

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

docs/SnapshotTesting.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,22 @@ Object {
210210
`;
211211
```
212212

213+
:::tip
214+
215+
If the case concerns a string not an object then you need to replace random part of that string on your own before testing the snapshot.
216+
You can use for that e.g. [`replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) and [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
217+
218+
```javascript
219+
const randomNumber = Math.round(Math.random() * 100);
220+
const stringWithRandomData = `<div id="${randomNumber}">Lorem ipsum</div>`;
221+
const stringWithConstantData = stringWithRandomData.replace(/id="\d+"/, 123);
222+
expect(stringWithConstantData).toMatchSnapshot();
223+
```
224+
225+
Another way is to [mock](MockFunctions.md) the library responsible for generating the random part of the code you're snapshotting.
226+
227+
:::
228+
213229
## Best Practices
214230

215231
Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively.

0 commit comments

Comments
 (0)