Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run some config before every Jest test run

I'm writing tests for a React application which makes use of Fluxxor to provide an event dispatcher. Making that work requires telling Jest not to mock a few modules which are used internally, and are provided by Node itself.

That means I can't just add them to the unmockedModulePathPatterns config key, and instead have to use some code like this:

[ 'util', 'events' ].forEach(function (module) {
  jest.setMock(module, require.requireActual(module));
});

However, I can't find anywhere useful to put it. I've got a setupEnvScriptFile which sets up a few globals that I use in almost all my tests, but the jest object doesn't seem to be available in that context, so I can't just set the mocks there.

As a hacky stopgap measure I've wrapped the code above in a function which I call at the beginning of any describe blocks testing Fluxxor stores, but its far from ideal.

like image 310
Jon Wood Avatar asked Jul 29 '14 14:07

Jon Wood


People also ask

What is before all in Jest?

beforeAll(fn, timeout) ​Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting.

Does beforeEach run before describe?

If beforeEach is inside a describe block, it runs for each test in the describe block. If you only need to run some setup code once, before any tests run, use beforeAll instead.

Which statement must be used to set fake timers before all the tests in a Jest JavaScript file?

Enable Fake Timers​useFakeTimers() . This is replacing the original implementation of setTimeout() and other timer functions. Timers can be restored to their normal behavior with jest.

What does cleanup do in Jest?

cleanup ​ Unmounts React trees that were mounted with render. Please note that this is done automatically if the testing framework you're using supports the afterEach global and it is injected to your testing environment (like mocha, Jest, and Jasmine).


1 Answers

Have you tried config.setupTestFrameworkScriptFile? Seems like it would be the right place to monkey patch the api, as per the docs.

like image 145
Naruto Sempai Avatar answered Nov 09 '22 16:11

Naruto Sempai