goldbergyoni / goldbergyoni/nodejs-testing-best-practices

Recipe idea: Stateful factory as a good pattern

Open
#34 5 comments 1 reaction 0 assignees View on GitHub
Dominant language
JavaScript
Stars
4.4k
Forks
288
PR merge metrics
No merged PRs in 30d

Description

It's too easy for integration test to step on each other toes by adding identical records when there is a unique constraint. For example, test 11 tries to add the user {name: 'messi'}, but also test 47 adds the same user. One of them will fail because 'name' is unique.

**Solution 1, what I used by now - Each test add a timestamp:**

`
const userToAdd = {name: `messi ${Math.random()}`)
`

**Solution 2, use a stateful factory - The test just calls some factory that manages the state and always provides fresh records:**
`
dataFactory.getUser('messi')//returns 'messi-55', or any unique number
`

A better approach might be to use some factory lib like rosie:
https://www.npmjs.com/package/rosie

Which one is better?

[Based on comments from @mikicho]

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.