Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one share assets across Jest Tests

Tags:

jestjs

How do I set up shared assets across test files?

For example, I have several variables, defined objects, that several tests should use. I also have many jest.mock() to also share across the bunch.

I tried an import of a class or something but nothing happens. To be fair, not sure what type of object I should create: class, function, unicorn, etc.?

I looked into creating my own TestEnvironment but can't see how this gets referenced by my tests. Everything I've seen says it just works. LIES!

This is a React app, latest versions of React and Jest, using create-react-app.

like image 433
David Lozzi Avatar asked Jan 25 '19 22:01

David Lozzi


People also ask

How does jest recognize a test file?

The pattern Jest uses to detect test files. By default it looks for . js and . jsx files inside of __tests__ folders, as well as any files with a suffix of .

Do you need to import jest?

In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them.

What is jest and how does it work?

Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly. Jest is well-documented, requires little configuration and can be extended to match your requirements.

How does jest mocking work?

Mocking is a technique to isolate test subjects by replacing dependencies with objects that you can control and inspect. A dependency can be anything your subject depends on, but it is typically a module that the subject imports.


1 Answers

For example, I have several variables, defined objects, that several tests should use.

We are using normal ES6 imports for that. Also it makes sense to try to avoid tight coulping for test suites.

I also have many jest.mock() to also share across the bunch.

You can use manual mock feature for that. Manual mocks are defined by writing a module in a mocks/ subdirectory immediately adjacent to the module.

To be fair, not sure what type of object I should create: class, function, unicorn, etc.?

Mock should be the same type and have the same interface as mocked entity.

like image 152
Dima Vishnyakov Avatar answered Jan 04 '23 06:01

Dima Vishnyakov