Solvedaphrodite Aphrodite + Jest error

I'm running an App that uses Aphrodite and Jest. After the test succeed, I get this error, related to Aphrodite:

/home/ricardo/Documents/Projects/reaxor/node_modules/aphrodite/lib/inject.js:29
        styleTag = document.querySelector("style[data-aphrodite]");
                           ^
TypeError: Cannot read property 'querySelector' of undefined
    at injectStyleTag (/home/ricardo/Documents/Projects/reaxor/node_modules/aphrodite/lib/inject.js:29:28)
    at flushToStyleTag (/home/ricardo/Documents/Projects/reaxor/node_modules/aphrodite/lib/inject.js:132:9)
    at RawTask.call (/home/ricardo/Documents/Projects/reaxor/node_modules/asap/asap.js:40:19)
    at flush (/home/ricardo/Documents/Projects/reaxor/node_modules/asap/raw.js:50:29)
    at /home/ricardo/Documents/Projects/reaxor/node_modules/jest-util/lib/FakeTimers.js:351:18
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
npm ERR! Test failed.  See above for more details.
24 Answers

✔️Accepted Answer

@green-arrow: I was able to solve this problem by returning a promise in the afterEach function:

afterEach(() => {
  return new Promise(resolve => {
    StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
    return process.nextTick(resolve);
  });
});

Other Answers:

still ran into the issue, with React 16.3.2, Jest 22.4.3, Aphrodite 2.2.0
via @saltycrane, found a perhaps cleaner solution here

here it is adapted to ES6, jestSetup.js:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as Aphrodite from 'aphrodite';
import * as AphroditeNoImportant from 'aphrodite/no-important';

Aphrodite.StyleSheetTestUtils.suppressStyleInjection();
AphroditeNoImportant.StyleSheetTestUtils.suppressStyleInjection();

Enzyme.configure({ adapter: new Adapter() });

then reference it in your package.json:

"jest": {
  "setupTestFrameworkScriptFile": "<rootDir>/jestSetup.js"
}

Using jest.runAllTimers() didn't work for me. Importing StyleSheetTestUtils and adding StyleSheetTestUtils.suppressStyleInjection() on beforeEach and StyleSheetTestUtils.clearBufferAndResumeStyleInjection() on afterEach worked fine.

@mrchess You should be able to add this in each test:

beforeEach(() => {
  StyleSheetTestUtils.suppressStyleInjection();
});
afterEach(() => {
  StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
});

But if you really want to use timers (and you shouldn't), you can add this into your Jest configuration:

"timers": "fake"

Try adding jest.runAllTimers() at the end of your test?

More Issues: