Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put common data in jest tests

I am not sure how to organize code for jest testing.

I have all my tests under __tests__ and all my mocks under __mocks__. Now I have some data I want to share between tests: they are not a mock of an existing function, they are just some javascript object I'd like to use in different files.

Should I create a __data__ directory?

Or put them under __mocks__ anyway?

Or in the __tests__ directory without putting -test in the file name?

like image 247
rpadovani Avatar asked Nov 16 '17 10:11

rpadovani


People also ask

Where do I put Jest mock data?

If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest. mock('module_name') .

Where are Jest test files stored?

src/file. test. js mentioned first in the Getting Started docs, and is great for keeping tests (especially unit) easy to find next to source files.

Is Jest enough for testing?

Jest is a JavaScript test runner that lets you access the DOM via jsdom . While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.

What is beforeAll and afterAll in Jest?

Jest provides beforeAll and afterAll . As with test / it it will wait for a promise to resolve, if the function returns a promise. beforeAll(() => { return new Promise(resolve => { // Asynchronous task // ...


1 Answers

The short answer is anywhere you want.

JavaScript has had a lot of different stages in its life and a lot of different types of people using it. Which is probably why most tools these days are highly configurable, to allow for personalization (customization.)

Even Jest itself shows these signs. For instance the test matcher will look for tests in either __tests__ folders or with files that are contain .spec or .test.

Or as per their docs in a visual manner:

├── __tests__ │   └── component.spec.js # test │   └── anything # test ├── package.json # not test ├── foo.test.js # test ├── bar.spec.jsx # test └── component.js # not test 

With regards to fixtures and other test files the answer is the same, there is no one way to do it.

Pick what works for you.

I recommend for the __tests__ structure placing fixture data close to the test thats using it, and if multiple tests need access then move it further up the project until its in a common place.

My preference is a tests folder to keep the tests, fixtures, and testing separate to the src code.

like image 64
noetix Avatar answered Sep 24 '22 14:09

noetix