Giter VIP home page Giter VIP logo

Comments (25)

smfoote avatar smfoote commented on June 4, 2024 20

@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);
  });
});

from aphrodite.

moarwick avatar moarwick commented on June 4, 2024 13

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"
}

from aphrodite.

niksajanjic avatar niksajanjic commented on June 4, 2024 9

@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"

from aphrodite.

Roilan avatar Roilan commented on June 4, 2024 8

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

from aphrodite.

sophiebits avatar sophiebits commented on June 4, 2024 6

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

from aphrodite.

jcperez-ch avatar jcperez-ch commented on June 4, 2024 6

Another possibly clever solution is to mock the injection by adding:

jest.mock('aphrodite/lib/inject');

from aphrodite.

niksajanjic avatar niksajanjic commented on June 4, 2024 3

I understand this issue is closed and it has been resolved and I appreciate that. But I would like to propose some documentation update. There's no mentioning of StyleSheetTestUtils nor it's API so I had to find this issue and then open source code to read exactly what these 2 functions do:

/**
 * Utilities for using Aphrodite in tests.
 *
 * Not meant to be used in production.
 */
const StyleSheetTestUtils = {
    /**
     * Prevent styles from being injected into the DOM.
     *
     * This is useful in situations where you'd like to test rendering UI
     * components which use Aphrodite without any of the side-effects of
     * Aphrodite happening. Particularly useful for testing the output of
     * components when you have no DOM, e.g. testing in Node without a fake DOM.
     *
     * Should be paired with a subsequent call to
     * clearBufferAndResumeStyleInjection.
     */
    suppressStyleInjection() {
        reset();
        startBuffering();
    },

    /**
     * Opposite method of preventStyleInject.
     */
    clearBufferAndResumeStyleInjection() {
        reset();
    },
};

It would be beneficial for other users to have it in docs, it would save them some time googling out issue that will always happen when using Jest and Aphrodite.

from aphrodite.

jlfwong avatar jlfwong commented on June 4, 2024

Not sure how jest works exactly, but Aphrodite injects styles into the <head> asynchronously immediately after a render(). If the jsdom instance that jest creates is torn down after the end of the test but before Aphrodite injects its styles, then I can see how this might happen.

from aphrodite.

KadoBOT avatar KadoBOT commented on June 4, 2024

@spicyj you are a beast 💃

from aphrodite.

jlfwong avatar jlfwong commented on June 4, 2024

@jcperez-ch That might work, but it's not part of the public API and is not guaranteed to not change in a minor or even patch version. We might e.g. move that file.

from aphrodite.

jlfwong avatar jlfwong commented on June 4, 2024

@niksajanjic That's a great point. Would be happen to take a PR documenting this feature, and I think it would fit comfortably above the Changelog section.

from aphrodite.

mrchess avatar mrchess commented on June 4, 2024

I also just ran into this issue... I fixed mine by adding this at the end of my test:

jest.useFakeTimers();
jest.runAllTimers();

But now I need to add it to every test... :(

from aphrodite.

smfoote avatar smfoote commented on June 4, 2024

The StyleSheetTestUtils solution only works for me when all tests are synchronous. If I have a async test, the error comes back. Anyone else seeing that?

from aphrodite.

green-arrow avatar green-arrow commented on June 4, 2024

I have the same problem as @smfoote. The StyleSheetTestUtils solution works just fine, but when trying to use it when testing a component with async behavior, the test suite fails with the same Cannot read property 'querySelector' of undefined.

from aphrodite.

green-arrow avatar green-arrow commented on June 4, 2024

@smfoote - that worked perfectly, thanks!

from aphrodite.

TobiasBales avatar TobiasBales commented on June 4, 2024

Interestingly enough using aphrodite with create-react-app-typescript the StyleSheetTestUtils fix does not work. When using the fake timer solution it does work, any ideas on how to figure this out?

from aphrodite.

danwoodbury avatar danwoodbury commented on June 4, 2024

I am using typescript and create-react-app (un-ejected) and I am still getting the error after trying all of the methods above. I want to keep using aphrodite but if it means I cannot run any tests then I will be forced to try something else. Unless someone can help fix it.

this is the test:

import * as React from 'react';
import * as renderer from 'react-test-renderer';
import { shallow } from 'enzyme';

import CollapseButton from '../../../components/SiteBuilderNew/CollapseButton/CollapseButton';

test('It renders correctly', () => {
    const onClickMock = jest.fn();

    const component = renderer.create(
        <CollapseButton onClick={onClickMock}>
            <div className="test">Test</div>
        </CollapseButton>
    );

    const tree = component.toJSON();

    expect(tree).toMatchSnapshot();
});

and the component:

import * as React from 'react';
import * as classNames from 'classnames';
import { css } from 'aphrodite';

import { CollapseButtonStyles } from './CollapseButton.styles';

interface CollapseButtonProps {
    onClick: () => void;
}

interface CollapseButtonState {

}

class CollapseButton extends React.Component<CollapseButtonProps, CollapseButtonState> {
    render () {
        const { children, onClick } = this.props;

        const buttonClasses = classNames(['CollapseButton', css(CollapseButtonStyles.collapseButton)]);

        return (
            <div className={buttonClasses} onClick={onClick}>
                {children}
            </div>
        );
    }
}

export default CollapseButton;

There is nothing particularly complicated about it but I just wanna test it.

Any help would be much appreciated

from aphrodite.

lencioni avatar lencioni commented on June 4, 2024

@danwoodbury can you put together a minimal repo that reproduces the issue to help us dig into it for you?

from aphrodite.

danwoodbury avatar danwoodbury commented on June 4, 2024

thanks @lencioni but the problem has been averted. I remembered that a while ago when I wasnt using create-react-app that if you had styles in a separate file then you had to do some funny webpack config to get it to work so i moved all of my aphrodite styles into the component file and by adding beforeEach and afterEach it works like a dream.

Also, ive come to realise this is a much better setup anyway than I had before

from aphrodite.

vpandura avatar vpandura commented on June 4, 2024

Thanks @moarwick

from aphrodite.

chriskuech avatar chriskuech commented on June 4, 2024

I'm getting this error in my create-react-app --typescript App, which is using the latest versions of everything. The confusing part is that I don't actually use aphrodite directly in my project--it appears all references to it are in one of my dependencies.

Does anyone know why one of my dependencies importing aphrodite is causing my Apps tests to fail? How do I stop aphrodite from affecting my App's test?

from aphrodite.

OneSpaceSolutionsEngineer avatar OneSpaceSolutionsEngineer commented on June 4, 2024

I am having this same issue in my application. The only place I have Aphrodite used is in my dependencies. I've tried all of the above fixes and my tests are still failing if I try to mount any of my components. The output I get is:

Call retries were exceeded
at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:193:21)

kages\task-ui-toolbox\node_modules\aphrodite\lib\chunk-e87a78a6.js:900
styleTag = document.querySelector("style[data-aphrodite]")
^
TypeError: Cannot read property 'querySelector' of null
at injectStyleTag (C:\dev\npm-packages\task-ui-toolbox\node_modules\aphrodite\lib\chunk-e87a78a6.js:900:25)
at flushToStyleTag (C:\dev\npm-packages\task-ui-toolbox\node_modules\aphrodite\lib\chunk-e87a78a6.js:1100:5)
at RawTask.Object..RawTask.call (C:\dev\npm-packages\task-ui-toolbox\node_modules\asap\asap.js:40:19)
at flush (C:\dev\npm-packages\task-ui-toolbox\node_modules\asap\raw.js:50:29)
at process._tickCallback (internal/process/next_tick.js:61:11)

from aphrodite.

tochidlife avatar tochidlife commented on June 4, 2024

@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"

Worked perfectly

from aphrodite.

codewithmide avatar codewithmide commented on June 4, 2024
afterEach(() => {
  StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
});

Thank you! this worked for me

from aphrodite.

moezbenrebah avatar moezbenrebah commented on June 4, 2024

Hello, is there any work around to test aphrodite styles using the RTL, because since I use:

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

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

In my test files, matches like "toHaveStyle" doesn't work, because in order to pass all RTL tests I have to prevent aphrodite styles injections.

Any alternatives or workaround to test aphrodite styles?

from aphrodite.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.