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?
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') .
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.
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.
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 // ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With