Git Product home page Git Product logo

enzyme-adapter-preact-pure's Introduction

enzyme-adapter-preact-pure

This is an adapter to support using the Enzyme UI component testing library with Preact. For documentation, please see the testing guide on the PreactJS website.

Supported Preact versions

Version 3.x of the adapter supports Preact v10+. Earlier versions support both Preact v8 and v10.

Usage

Add the library to your development dependencies:

# If using npm
npm install --save-dev enzyme-adapter-preact-pure

# If using yarn
yarn add --dev enzyme-adapter-preact-pure

Then in the setup code for your tests, configure Enzyme to use the adapter provided by this package:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';

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

Once the adapter is configured, you can write Enzyme tests for your Preact UI components following the Enzyme docs. The full DOM rendering, shallow rendering and string rendering modes are supported.

Example projects

For runnable example projects, see the examples/ directory. To run the examples locally, clone this repository, then run:

cd examples/<project name>
npm install
npm test

Differences compared to Enzyme + React

The general intent is that tests written using Enzyme + React can be easily made to work with Enzyme + Preact or vice-versa. However there are some differences in behavior between this adapter and Enzyme's React adapters to be aware of:

Shallow rendering

  • When using Enzyme's shallow rendering mode, this adapter always invokes the component's lifecycle methods (componentDidUpdate etc.). The disableLifecycleMethods option is not respected.

  • React's shallow rendering does not create actual DOM nodes. The shallow rendering implemented by this adapter does. It works by simply by rendering the component as normal, except making any child components output only the children passed to them. In other words, during shallow rendering, all child components behave as if they were defined like this:

    function ShallowRenderedChild({ children }) {
      return children;
    }

    This means that any side effects that rendered DOM elements have, such as <img> elements loading images, will still execute.

If you are converting a React Enzyme test suite to use Preact, try out our CompatShallowRenderer. This renderer is an alternate shallow renderer to the default that uses a custom diffing algorithm that mirrors the Preact diff algorithm but only shallowly renders elements, similarly to what react-shallow-render does for React components. This renderer has a couple of behaviors that more closely resembles the React adapters, including:

  • No DOM nodes are created, so a DOM environment is not required
  • disableLifecycleMethods option is respected
  • Virtual element props are preserved intact so filter methods on the Enzyme wrapper behave more similarly to the React wrappers

To enable the CompatShallowRenderer, pass it into the shallowRenderer Adapter option when configuring Enzyme:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';
import { CompatShallowRenderer } from 'enzyme-adapter-preact-pure/compat';

// Setup Enzyme
configure({
  adapter: new Adapter({
    ShallowRenderer: CompatShallowRenderer,
  }),
});

Simulating events

The simulate API does not dispatch actual DOM events in the React adapters, it just calls the corresponding handler. The Preact adapter does dispatch an actual event using element.dispatchEvent(...). Because this behavior, the Preact adapters can only simulate events on real DOM nodes, not Components.

If you'd like to simulate events on Components, enable the simulateEventsOnComponents option in the Adapter options. This option changes the previous behavior of how events were dispatched (by directly invoking event handlers instead of dispatching an event) and so is disabled by default. Enabling this option is useful if you are migrating an Enzyme test suite from React to Preact.

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';

// Setup Enzyme
configure({
  adapter: new Adapter({
    simulateEventsOnComponents: true,
  }),
});

String rendering

By default, the Preact string renderer renders your component into the DOM and then returns the innerHTML of the DOM container. This behavior means string rendering requires a DOM environment.

If you'd like to run tests that use the string renderer in a test environment that does not have a DOM, pass preact-render-to-string into the renderToString Adapter option. Enabling this option is useful if you are migrating an Enzyme test suite from React to Preact.

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';
import renderToString from 'preact-render-to-string';

// Setup Enzyme
configure({
  adapter: new Adapter({
    renderToString,
  }),
});

State updates

setState synchronously re-renders the component in React, except in event handlers. Preact on the other hand by default batches together calls to setState within the same tick of the event loop and schedules a render to happen in a future microtask. React's behavior may change in a future release.

To make writing tests easier, the Preact adapter will apply any pending state updates and re-render when:

  • The component is initially rendered by mount or shallow
  • An Enzyme API call is made that is expected to trigger a change in the rendered output, such as wrapper.setProps, wrapper.simulate or wrapper.setState
  • wrapper.update is called explicitly by a test

The consequences of this when writing tests are that any state updates triggered outside of an Enzyme method call will not be reflected in the rendered DOM until wrapper.update is called. Note this function also needs to be called when using React, as it synchronizes Enzyme's snapshot of the output with the actual DOM tree.

Example:

const wrapper = shallow(<ParentComponent />);

// Trigger a state update outsize of Enzyme.
wrapper.find(ChildComponent).props().onClick();

// Update the Enzyme wrapper's snapshot.
wrapper.update();

// Test that parent component updated as expected.

When using the Hooks API you also need to wrap any code which triggers effects in an act call in order to flush effects and trigger a re-render. The initial render and calls to APIs such as setProps or simulate are automatically wrapped in act for you.

In Preact the act function is available in the "preact/test-utils" package.

import { act } from 'preact/test-utils';

// Any effects scheduled by the initial render will run before `mount` returns.
const wrapper = mount(<Widget showInputField={false} />);

// Perform an action outside of Enzyme which triggers effects in the parent
// `Widget`. Since Enzyme doesn't know about this, we have to wrap the calls
// with `act` to make effects execute before we call `wrapper.update`.
act(() => {
  wrapper.find(ChildWidget).props().onButtonClicked();
});

// Update the Enzyme wrapper's snapshot
wrapper.update();

Property names

In order to support Enzyme's class selectors, class props on Preact components are mapped to className.

import { mount } from 'enzyme';

const wrapper = mount(<div class="widget" />);
wrapper.props(); // Returns `{ children: [], className: 'widget' }`
wrapper.find('.widget').length; // Returns `1`

Usage with preact/compat

This package has the same interface as the official enzyme-adapter-react-$version packages. If you are using preact/compat, you can alias enzyme-adapter-react-$version to this package in the same way as preact/compat.

Usage with TypeScript

This package is compatible with TypeScript and ships with type declarations. In order to mix Enzymes types from @types/enzyme with Preact, you will need to include some extensions to the "preact" types which are provided by this project.

To do that, add the following line to one of the source files or .d.ts files for your project:

/// <reference types="enzyme-adapter-preact-pure" />

See the TypeScript example in examples/typescript for a runnable example.

Development

After cloning the repository, you can build it and run tests as follows:

# Install dependencies.
yarn install

# Build the adapter library.
yarn build

# Run tests.
yarn test

# Run tests against a custom build of Preact.
yarn test --preact-lib <path to Preact bundle>

Release process

New releases of this package are created using np.

  1. Check out the latest master branch
  2. Edit CHANGELOG.md to add notes for the version you are about to release.
  3. Commit the changes to CHANGELOG.md and push back to GitHub
  4. Run np <semver-type> to create the release, where <semver-type> is the category of release according to Semantic Versioning, typically minor.

FAQ

Can I use this library to test components that use hooks?

Yes. This library supports components that use the "Hooks" APIs available in Preact v10+. You may need to use the act function from preact/test-utils to flush effects synchronously in certain places. See the notes above about state updates in tests.

Why does the package name have a "-pure" suffix?

The name has a "-pure" suffix to distinguish it from enzyme-adapter-preact package which indirectly depends on React. This library is a "pure" Preact adapter which does not require Preact's React compatibility add-on.

enzyme-adapter-preact-pure's People

Contributors

andrewiggins avatar bartwaardenburg avatar d3x7r0 avatar dependabot-support avatar dependabot[bot] avatar developit avatar greenkeeper[bot] avatar kevinweber avatar marvinhagemeister avatar robertknight avatar rschristian avatar wnayes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

enzyme-adapter-preact-pure's Issues

An in-range update of preact is breaking the build 🚨

The devDependency preact was updated from 10.0.2 to 10.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

preact is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 17 commits.

  • 88999fe Release 10.0.3 (#2058)
  • cb51e15 Fix setState warning always being printed (#2057)
  • dd66bc6 Queue layoutEffects in component render callbacks array (+0 B) (#2050)
  • d013647 Separate debug tests into multiple files and fix some bugs in debug (#2047)
  • 51057f2 Merge branch 'master' into feat/rework-debug-tests
  • 96ab769 Remove unnecessary string ref test
  • b0d6228 Delete bugging WeakMap implementation and only use real WeakMaps
  • e4dd728 Use defineProperty to try and hide weakMap prop
  • cc2e5c8 Remove duplicate devtools option test
  • 06e7f6c Use a WeakMap to track which components have warned already
  • e3c2308 Add WeakMap polyfill
  • 2a66c26 Add comment explaining why remaining tests are failing
  • e66d37e Use getDisplayName in a couple more places in debug
  • f408eec Clarify the difference between some debug suspense tests
  • e5f750c Fix argumentless useLayoutEffect debug test

There are 17 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Cannot test Legacy Context API

Hi,

I'm trying to test a component using Legacy Context API but the context doesn't seems to be reaching the test file.

The app:

// App.js
export default class App extends Component {
  getChildContext() {
    return { name: "Pipo" };
  }
  render() {
    return <div><Hello /></div>;
  }
}

// Hello.js
export default class Hello extends Component {
  render() {
    return <h1>Hello {this.context.name}!</h1>;
  }
}

The test:

import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-preact-pure";
import Hello from "./Hello";

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

it("works", () => {
  const wrapper = shallow(<Hello />, {
    context: { name: "Pepe" }
  });
  expect(wrapper.context("name")).toEqual("Pepe");
});

The test fails with:

Expected value to equal:
  "Pepe"
Received:
  undefined

It seems the context parameter is not being used. Or am I missing something?

You can see a (not) working example here.

Thanks.

Tests fail when a function is passed as prop

Hello! I'm trying to use this adapter on a project running on the latest preact (v10.0.0-beta.1).

However I've found a big issue when I try to test components which pass functions to their children as props, they yield me this error (I'm using jest as test runner):

ReferenceError: self is not defined

      at oldValue (node_modules/preact/src/diff/props.js:79:9)
      at isSvg (node_modules/preact/src/diff/props.js:16:68)
      at A (node_modules/preact/src/diff/index.js:298:1)
      at ref (node_modules/preact/src/diff/index.js:178:17)
      at x (node_modules/preact/src/diff/children.js:89:22)
      at A (node_modules/preact/src/diff/index.js:285:67)
      at ref (node_modules/preact/src/diff/index.js:178:17)
      at b (node_modules/preact/src/diff/index.js:156:15)
      at x (node_modules/preact/src/diff/children.js:89:22)
      at Object.EMPTY_OBJ [as render] (node_modules/preact/src/render.js:25:3)

This render function yields the error:

export default function Dummy({ name, onChange }) {
    return (
        <div className="foobar">
            <h1>Hello {name}!</h1>
            <select name="field" onSomething={onChange}>
                {options.map(o => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                ))}
            </select>
        </div>
    );
}

while this not:

export default function Dummy({ name, onChange }) {
    return (
        <div className="foobar">
            <h1>Hello {name}!</h1>
            <select name="field">
                {options.map(o => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                ))}
            </select>
        </div>
    );
}

I'm testing this componente like this:

import { h } from 'preact';
import { shallow } from 'enzyme';

import Dummy from './../src/Dummy';

describe('<Dummy />', () => {
    test('First render', () => {
        const tree = shallow(<Dummy name="World" onChange={value => console.log(value)}/>);

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

I've created an example repo to better show off the problem here.

I've tried to track the bug but with no success, the stacktrace does not make much sense to me :/

Remove dependencies on Preact internals

The Preact v10 support currently relies on some internal details of Preact, in particular the mangled property names of rendered VNodes.

For longer term maintainability, it would be a good idea to add support for extracting the necessary information from about the rendered VNode tree via a public API (see upstream PR) and then to modify this library to use it.

Enzyme `contains` example from Enzyme docs does not pass

I've noticed a discrepancy between Enzyme's documentation and the behavior with this adapter. The difference doesn't seem to be explained by the current list of differences.

I'm looking specifically at this API:
https://airbnb.io/enzyme/docs/api/ShallowWrapper/contains.html

And these examples:

const wrapper = shallow((
  <div>
    <div data-foo="foo" data-bar="bar">Hello</div>
  </div>
));

expect(wrapper.contains(<div data-foo="foo" data-bar="bar">Hello</div>)).to.equal(true);

expect(wrapper.contains(<div data-foo="foo">Hello</div>)).to.equal(false);
expect(wrapper.contains(<div data-foo="foo" data-bar="bar" data-baz="baz">Hello</div>)).to.equal(false);
expect(wrapper.contains(<div data-foo="foo" data-bar="Hello">Hello</div>)).to.equal(false);
expect(wrapper.contains(<div data-foo="foo" data-bar="bar" />)).to.equal(false);

The last expectation fails when ran with this adapter.

// This one fails:
expect(wrapper.contains(<div data-foo="foo" data-bar="bar" />)).to.equal(false);

I have a code sandbox here that demonstrates the assertion failure:
https://codesandbox.io/s/snowy-cache-q6hzg

My suspicion is that it has something to do with handling of the children prop.

Avoid confusing behaviour caused by deferred hook execution

After-paint actions scheduled with useEffect are currently scheduled to execute using requestAnimationFrame followed by a setTimeout(callback, 0) by default. It isn't very obvious how to:

  • Make any pending effects execute and update the Enzyme wrapper to reflect the final rendered state
  • Clean up properly at the end of a test

From what I gather, this is the not-very-clearly explained purpose of act() (React docs).

I think what we'll want to do here is:

  1. Wrap the initial render in act() so that all effects have executed by the time the developer starts interacting with the returned wrapper
  2. Wrapper event dispatches and other updates through the wrapper in act for the same reason
  3. Make sure there is documentation in place about what to do for manipulations of components that happen outside of the wrapper (timeouts, events manually dispatched to DOM elements etc.)
  4. Try to figure out how to simplify cleanup at the end of a test

I also wonder whether the adapter should automatically register a replacement for options.requestAnimationFrame, since we want tests to execute as fast as possible.

No `LICENSE` file

The preact project has a LICENSE file, but I don't see one here. I can see that the project.json suggests this is MIT licensed, but I don't know if that counts as "official" or not (Github does not indicate it as so). Could a LICENSE file be added?

Argument of type Element is not assignable

I'm trying to migrate my project over to preact 10.0.0 and enzyme/enzyme-adapter-preact-pure, however I'm having trouble with types.

Component

import { h, Component } from 'preact';
import { RoutableProps } from 'preact-router';

import { Tracklist, FetchTracklists } from '../services/memoir/types';

import TracklistItem from '../components/TracklistItem';

interface Props extends RoutableProps {
  fetchTracklists: FetchTracklists;
}

interface State {
  isLoading: boolean;
  tracklists: Tracklist[] | null;
}

export default class TracklistsPage extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { isLoading: false, tracklists: null };
  }

  async componentWillMount() {
    // ...
  }

  renderTracklists() {
    // ...
  }

  render() {
    // ...
  }
}

Test

import { h } from 'preact';
import { mount, configure } from 'enzyme';
import { Adapter } from 'enzyme-adapter-preact-pure';
import test from 'ava';

import TracklistsPage from '../../src/pages/Tracklists';

import { FetchTracklists } from '../../src/services/memoir/types';

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

test('renders empty tracklists component', async t => {
  const fetchStub: FetchTracklists = () => new Promise(resolve => resolve([]));

  const wrapper = mount(<TracklistsPage fetchTracklists={fetchStub} />);

  // TODO: implement proper tests

  t.truthy(wrapper, 'TODO');
});

Error message

  Uncaught exception in test/pages/Tracklists.test.tsx

  test/pages/Tracklists.test.tsx:12:25 - error TS2345: Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>'.
    Types of property 'type' are incompatible.
      Type 'string | ComponentClass<any, {}> | FunctionComponent<any> | null' is not assignable to type 'string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)'.
        Type 'null' is not assignable to type 'string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)'.

  12   const wrapper = mount(<TracklistsPage fetchTracklists={fetchStub} />);
                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

compatibility issue with typescript and function component

Hey, im using enzyme-adapter-preact-pure in preact project with typescript, everything works well until I'm using React function component (not class component) I'm getting this type error -

Error:(5, 9) TS2605: JSX element type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>' is not a constructor function for JSX elements. Type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>' is missing the following properties from type 'Element': nodeName, attributes, children

preact runs this component with no issue, what should i do ?

Typescript example does not work

The example referenced in the documentation and contained in the repository does not work out of the box. This makes it hard to find out how to configure a typescript based project to work with this.

Steps to Reproduce

  1. git clone https://github.com/preactjs/enzyme-adapter-preact-pure.git
  2. cd enzyme-adapter-preact-pure/examples/typescript
  3. npm install
  4. npm test

Expected Behavior

Tests pass

Current Behavior

Compilation errors.

Possible Solution

Aside from a couple of type declarations (@types/jsdom, @types/chai, possibly others) missing, even after installing those I couldn't get it to work. The example could use an upgrade to v3 of the library as well.

Synchronous `setState` can cause incorrect output

The adapter monkey-patches a component's setState method so that it triggers a synchronous update, as opposed to Preact's default behaviour which is to mark the component as "dirty" and schedule a future re-render. This can cause incorrect output if a state setter returned by useState is called in the middle of a render, a pattern that the React docs specifically recommend for certain use cases.

Steps to reproduce:

Consider this test case of an input field which renders an initial value and allows the user to edit the value, but resets it whenever the value prop changes. The component uses a React hooks idiom for updating state in response to prop changes.

let n = 0;
function InputWidget({ value }) {
  const rid = n++;
  const [prevValue, setPrevValue] = useState(value);
  const [pendingValue, setPendingValue] = useState(value);
                                                                                                          
                                                                                                          
  if (value !== prevValue) {
    setPrevValue(value);
    setPendingValue(value);
  }
                                                                                                          
  console.log(`render ${rid} with value ${value}, prevValue ${prevValue}, pendingValue ${pendingValue}`);
                                                                                                          
  return (
    <input
      value={pendingValue}
      onInput={e => setPendingValue(e.target.value)}
    />
  );
}
                                                      
const wrapper = mount(<InputWidget value="foo"/>);
                                                                    
// Check initial render.
assert.equal(wrapper.find('input').prop('value'), 'foo');
                                                                    
// Simulate user typing and check that their edit is displayed.
wrapper.find('input').getDOMNode().value = 'pending-value';
wrapper.find('input').simulate('input');
assert.equal(wrapper.find('input').prop('value'), 'pending-value');
                                                                    
// Change prop and check that user-entered value was overwritten.
wrapper.setProps({ value: 'bar' });

// Assert fails with `expected 'pending-value' to equal 'bar'`
assert.equal(wrapper.find('input').prop('value'), 'bar');

Expected result:. Test passes
Actual result:

Test fails on the last assertion. The console log output is:

LOG: 'render 0 with value foo, prevValue foo, pendingValue foo'
LOG: 'render 1 with value foo, prevValue foo, pendingValue pending-value'
LOG: 'render 3 with value bar, prevValue bar, pendingValue pending-value'
LOG: 'render 4 with value bar, prevValue bar, pendingValue bar'
LOG: 'render 2 with value bar, prevValue foo, pendingValue pending-value'

The synchronous updates caused by the set{PrevValue, PendingValue} calls in the middle of a render result in incorrect final output, because renders 3 & 4 start after 2 but complete before it.

Workaround

Commenting out the setState monkey-patching in the adapter fixes the problem.

simulate(): TypeError: Cannot set property target of [object Event] which has only a getter

I have the following Enzyme code that worked when my project used React, but stopped working when I switched to Preact:

wrapper.find("input#number-input")
  .simulate("change", { target: { valueAsNumber: 16 }});

The error now:

TypeError: Cannot set property target of [object Event] which has only a getter

I found and looked through issue #46, and tried several approaches suggested there (adding a /// <reference, and casting the wrapper to any), but none helped.

Non-vnode children not supported with shallow rendering

If I try to shallow render a component that makes use of children in an unusual way (a "render prop" pattern for example) I encounter errors. Specifically, I hit Preact's "Objects are not valid as a child. Encountered an object with the keys..." message.

An example scenario is something like this:

function MyComponent(props) {
    return (
        <RenderPropExample>
            {() => <div>Example</div>}
        </RenderPropExample>
    );
}

function RenderPropExample(props) {
    return props.children();
}

const wrapper = shallow(<MyComponent />);

The issue appears to be that the ShallowRenderStub unconditionally returns its children.

In the example above, the ShallowRenderStub created for RenderPropExample would end up returning the render prop child function, which is not what the real RenderPropExample would do.

Preact then sees the non-vnode children that were returned by the ShallowRenderStub, and throws its debug error.

If I patch the adapter locally to make the ShallowRenderStub be a bit more picky about whether to return children, the issue goes away. (I need to then dive() through to get the render prop to execute, but that seems reasonable.) I'm not sure exactly what the perfect check would be, but I think even an approximate check would go a long way to avoid this in most practical cases.

Preact useState/useEffect Value Problem

Hello;

I've been trying (unsuccessfully) to test a component that performs asynchronous fetching of data as an effect in order to update state, which should get reflected upon the next render. What happens is that when I query the mounted component via Enzyme, I only see the initial state's value, and not the value that the state should be finally set to. I've tried adding setTimeouts in my test code, wrapping things in act, but nothing seems to work.

I've boiled this down into the simplest code that can replicate my issue. For reference, I'm utilizing jest v24.9.0, preact v10.0.0-rc.1, enzyme v3.10.0 and enzyme-adapter-preact-pure v2.0.2. Below is a simplified synchronous and asynchronous example, as I've found that the same issue is happening to me in both scenarios:

import {configure, mount} from 'enzyme';
import {PreactAdapter} from 'enzyme-adapter-preact-pure';
import {h} from 'preact';
import {useEffect, useState} from 'preact/hooks';

beforeAll(() => {
    configure({adapter: new PreactAdapter});
});

test('handles promised effect/state combo', () => {
    const wrapper = mount(<PromisedEffect/>);
    wrapper.update();

    console.debug(wrapper.html());
    expect(wrapper.find('p').text()).toEqual('goodbye');
});

function PromisedEffect() {
    let [value, setValue] = useState('hello');
    useEffect(() => {
        Promise.resolve('goodbye').then(v => setValue(v));
    });

    console.debug('Promised Render Value:', value);

    return <p>{value}</p>;
}

test('handles standard effect/state combo', () => {
    const wrapper = mount(<StandardEffect/>);
    wrapper.update();

    console.debug(wrapper.html());
    expect(wrapper.find('p').text()).toEqual('goodbye');
});

function StandardEffect() {
    let [value, setValue] = useState('hello');
    useEffect(() => {
        setValue('goodbye');
    });

    console.debug('Standard Render Value:', value);

    return <p>{value}</p>;
}

Running this via the Jest test runner gives the following output:

 FAIL  src/effect.test.js
  × handles promised effect/state combo (33ms)
  × handles standard effect/state combo (8ms)

  ● handles promised effect/state combo

    expect(received).toEqual(expected) // deep equality

    Expected: "goodbye"
    Received: "hello"

      13 | 
      14 |     console.debug(wrapper.html());
    > 15 |     expect(wrapper.find('p').text()).toEqual('goodbye');
         |                                      ^
      16 | });
      17 | 
      18 | function PromisedEffect() {

      at Object.toEqual (src/effect.test.js:15:38)

  ● handles standard effect/state combo

    expect(received).toEqual(expected) // deep equality

    Expected: "goodbye"
    Received: "hello"

      32 | 
      33 |     console.debug(wrapper.html());
    > 34 |     expect(wrapper.find('p').text()).toEqual('goodbye');
         |                                      ^
      35 | });
      36 | 
      37 | function StandardEffect() {

      at Object.toEqual (src/effect.test.js:34:38)

  console.debug src/effect.test.js:24
    Promised Render Value: hello

  console.debug src/effect.test.js:14
    <p>hello</p>

  console.debug src/effect.test.js:24
    Promised Render Value: goodbye

  console.debug src/effect.test.js:43
    Standard Render Value: hello

  console.debug src/effect.test.js:33
    <p>hello</p>

Test Suites: 1 failed, 1 total
Tests:       2 failed, 2 total
Snapshots:   0 total
Time:        5.074s, estimated 7s
Ran all test suites matching /effect.test.js/i.

I've been banging my head on this for a while, and it doesn't seem to be specific to how I'm writing my test code, but then again, maybe I'm missing something.

Debounce install hook doesn't work for Preact X RC1

The conditional code in installHook to handle the Preact X case, breaks for the RC1 release.

The comment there says only applicable for an old Preact X beta build, which I assume isn't that relevant anymore?

Example output:

image

I've just deleted the Preact X conditional section and it seems to work fine: https://github.com/lowaa/enzyme-adapter-preact-pure/blob/master/src/debounce-render-hook.ts

Didn't make a PR because this will break for the beta build of Preact X

Update mount adapter so that events bubble by default

In the simulateEvent handler in the Mount renderer, events do not bubble by default.

While this matches the shallow behavior, it is different from how the Enzyme React adapter works. With the React adapter, shallow triggers behavior by calling the method on props, but mount utilizes React's event system.

ReactWrapper

ShallowWrapper

If the mount simulateEvent bubbling is changed to default to true, then we would keep parity between how React and Preact adapters work.

Thanks!

Testing Stateful Functional Components

Hi,

There is anyway to check the state of a functional component that implements the state with the hook useState? I tried the mount.state() but it says that can be only used on Class components.

I saw that Preact 10 now includes preact/test-utils that should help with this but I could find a way to use it with enzyme and get the state.

My idea is to get the state and see if the values are what I expect. But maybe there are better way to test the component state.

Add runnable examples to the repository

Add some basic examples to the repository showing various ways to test components and link to them near the top of the README so newcomers can find them easily.

These examples should cover:

  • Basic DOM rendering of a simple component
  • Shallow rendering
  • Testing components with effects and state updates

I don't want to repeat what is already covered in the Enzyme docs too much, but I think there would be value in having some complete runnable examples.

This does not work in Preact 10.0.0-beta.2

I use 1.13.1.
This works in Preact 10.0.0-beta.1.
This does not work in Preact 10.0.0-beta.2.

     TypeError: Cannot read property 'setState' of undefined
      at MountRenderer.render (node_modules/enzyme-adapter-preact-pure/build/src/MountRenderer.js:45:22)
      at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:134:16)
      at mount (node_modules/enzyme/build/mount.js:21:10)

Jest encountered an unexpected token export with the adapter

I'm trying to set up a new project, and simply adding these give me an error:

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-preact-pure";

configure({ adapter: new Adapter() });
SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1773:14)
      at Object.<anonymous> (node_modules/enzyme-adapter-preact-pure/build-cjs/src/Adapter.js:8:18)

In the details of the error, it looks like it might be trying to parse the preact.module.js file?

Details:

    /projects/x/node_modules/preact/dist/preact.module.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){var n,l,u,i,t,o,r,f={}....

Not sure exactly what's going on. Am I missing an obvious option?

An in-range update of enzyme is breaking the build 🚨

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.9.0 to 3.10.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the enzyme group definition.

enzyme is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Breaking changes planned for v3.0.0

This is a list of breaking changes planned for the next major release of this adapter. There is currently no time-frame for when that release will be published: Update: This release is planned for January 2021

  • Drop support for Preact v8 and Preact v8's React compatibility package (preact-compat) See #126.

Tests only work for functional components but fail for class components

in Adapter.ts, isValidElement checks for -

if (
      typeof el.type !== 'string' &&
      typeof el.type !== 'function' &&
      el.type !== null
    ) {
      return false;
    }

but type is always undefined for class based components.

System:
OS: macOS 10.14.6
CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Binaries:
Node: 10.16.3 - /usr/local/bin/node
Yarn: 1.21.1 - /usr/local/bin/yarn
npm: 6.11.3 - /usr/local/bin/npm
Browsers:
Chrome: 79.0.3945.130
Safari: 13.0.5
npmPackages:
preact: ^10.2.1 => 10.2.1
preact-cli: 3.0.0-rc.4 => 3.0.0-rc.4
preact-render-to-string: ^5.1.3 => 5.1.3
preact-router: ^3.1.0 => 3.1.0

Expected VDOM node to be a DOM node but got undefined - piocstyle/preact x beta 3

When rendering components using mount I get the error:

Expected VDOM node to be a DOM node but got undefined

After some debugging I noticed the offending components do not have an __e at top level which is required by https://github.com/preactjs/enzyme-adapter-preact-pure/blob/master/src/preact10-internals.ts#L87,

rather they have only a __p (parent?) property.

Example console dump of a picostyle styled i tag:

{ __p:
         { type: 'i',
           props:
            { size: 20,
              iconName: 'image',
              styles: [Object],
              class: 'p1',
              children: [Circular] },
           key: undefined,
           ref: undefined,
           __k: [ [Circular] ],
           __p:
            { type: [Function],
              props: [Object],
              key: undefined,
              ref: undefined,
              __k: [Array],
              __p: [Object],
              __b: 5,
              __e: HTMLElement {},
              l: null,
              __c: [y],
              constructor: undefined },
           __b: 6,
           __e: HTMLElement {},
           l: null,
           __c: null,
           constructor: undefined },
        __b: 7 }

I use picostyle to render components but it still defers to Preact's h, so I'm not sure if this is a picostyle issue or a compatibility issue in enzyme-adapter-preact-pure. My lack of knowledge around how Preact's rendering does/should work means I'm quite stumped here, is it valid for only a __p to exist?

EDIT: also this is using latest version of adapter. 2.0.0

Error: Expected VDOM node to be a DOM node but got function Ref(props)

I have set up a project using vite, vitest, preact, enzyme and this very adapter. You can find a small(-ish) repository to reproduce a problem I encountered here: https://github.com/heyarne/vitest-semantic-ui-preact

The repository contains two components. For one tests work fine, for the other they don't. I have detailed this in the README of the linked repository.

npm test src/Counter.test.jsx # works fine, pure preact component
npm test src/SemanticButton.test.jsx # does not work

The second command is failing with the message given in this issue's title. The difference is that I'm trying to use a component from https://github.com/Semantic-Org/Semantic-UI-React/, which somehow confuses enzyme-addapter-preact-pure (vite build works fine, but mounting the component in a test does not). The full error message is this:

 FAIL  SemanticButton.test.jsx > SemanticButton > should mount component
Error: Expected VDOM node to be a DOM node but got function Ref(props) {
  var children = props.children,
      innerRef = props.innerRef,
      rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
  var child = React.Children.only(children);
  var ElementType = ReactIs.isForwardRef(child) ? _RefForward.RefForward : _RefFindNode.RefFindNode;
  var childWithProps = child && rest && Object.keys(rest).length > 0 ? /*#__PURE__*/React.cloneElement(child, rest) : child;
  return /*#__PURE__*/React.createElement(ElementType, {
    innerRef: innerRef
  }, childWithProps);
}
 ❯ rstNodeFromVNode ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:73:15
 ❯ ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:50:21
 ❯ rstNodesFromChildren ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:42:18
 ❯ rstNodeFromComponent ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:136:22
 ❯ rstNodeFromVNode ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:70:16
 ❯ ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:50:21
 ❯ rstNodesFromChildren ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:42:18
 ❯ rstNodeFromComponent ../node_modules/enzyme-adapter-preact-pure/build-cjs/src/preact10-rst.js:136:22

It looks like the issue is similar to #61, but I'm not entirely sure how both relate to each other.

The component raising the error is (I think) this one: https://github.com/microsoft/fluentui/blob/1a0f15ed7ea41974e3ef6cf83138b60656dacd7c/packages/fluentui/react-component-ref/src/Ref.tsx Any idea why this confuses this adapter? Is there anything I can do about it?

Thanks in advance!

Usage with declared preact/compat type

Hello, There is a type conflict with the preact/compat type.

tsconfig.json

"paths": {
      "react": ["node_modules/preact/compat"],
      "react-dom": ["node_modules/preact/compat"],
      "linaria/react": ["src/utils/styled.ts"]
}

I alias react and react-dom type to preact/compat for use linaria/react(CSS in JS module) in typescript project.

type check result

❯ yarn tsc
yarn run v1.19.1
warning ../../../package.json: No license field
$ /Users/muhun/github/reflation/extension/node_modules/.bin/tsc
node_modules/@types/enzyme/index.d.ts:22:5 - error TS2724: preact/compat has no exported member 'ReactElement'. Did you mean 'createElement'?

22     ReactElement,
       ~~~~~~~~~~~~

node_modules/@types/enzyme/index.d.ts:30:14 - error TS2515: Non-abstract class 'ElementClass' does not implement inherited abstract member 'render' from class 'Component<any, any>'.

30 export class ElementClass extends Component<any, any> {}

The error in above not appear when remove preact/compat type alias. but another type error appear in react library. How can I solve it?

`enzyme-adapter-preact-pure` is not working with TypeScript

It seems the types declared in types/enzyme/index.d.ts are conflicting with the one from @types/enzyme. I get 12 errors stating that @types/enzyme has no exported member 'member'.

Proposed solution: use @types/enzyme instead.
Edit: I was wrong about the cause of the errors.

Jest fails to parse TSX

Hello, I'm trying to run tests with Jest in a Preact app with TypeScript. I get a Jest encountered an unexpected token error :

FAIL  src/app/app.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, 
     e.g. it's not plain JavaScript.
...
    Details:

    src/app/app.test.tsx:10
        const wrapper = enzyme_1.mount(<app_1.default optOutUrl="none"/>);
                                       ^

    SyntaxError: Unexpected token <

    at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)

After seen TypeScript example in this enzyme-adapter-preact-pure, I Changing jsx option to react in tsconifg.json. But It not helpful for my project environment:

Cannot find module 'react' from 'styled.js'

    However, Jest was able to find:
        './styled.js'
        './styled.js.flow'
        './styled.js.map'

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:276:11)
      at Object.<anonymous> (node_modules/linaria/src/react/styled.js:3:15)

In the above error, it says that react parsing failed in the styled component related file. (I’m use styled components from linaria/react with custom Preact typing.) this issue not appear in development and production environment.

I also tried using babel-jest with below config. But I got the same message as the first error log.

“transform”: {
      “^.+\\.ts$”: “babel-jest”
    }

An in-range update of ts-node is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency ts-node was updated from 8.9.1 to 8.10.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

ts-node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for Experimental native ESM support

Added

Experimental support for native ECMAScript modules in node >=13 (#1007, #1010)

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Typescript example still does not work

This is not a duplicate of issue #198. Tests build, run and succeed in a terminal. However they do not in VS Code, because of conflicting React types:

Bildschirm­foto 2022-12-09 um 10 35 21

The error is:

No overload matches this call.
  Overload 1 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<...>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
      Types of property 'type' are incompatible.
        Type 'string | ComponentType<any>' is not assignable to type 'string | JSXElementConstructor<any>'.
          Type 'ComponentClass<any, {}>' is not assignable to type 'string | JSXElementConstructor<any>'.
            Type 'ComponentClass<any, {}>' is not assignable to type 'new (props: any) => Component<any, any, any>'.
              Property 'refs' is missing in type 'Component<any, {}>' but required in type 'Component<any, any, any>'.
  Overload 2 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<...>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.
  Overload 3 of 3, '(node: ReactElement<any, string | JSXElementConstructor<any>>, options?: MountRendererProps | undefined): ReactWrapper<...>', gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>>'.ts(2769)
index.d.ts(507, 9): 'refs' is declared here.

This is the typescript example straight checked-out, initialized and opened in VS Code.

An in-range update of preact is breaking the build 🚨

The devDependency preact was updated from 8.4.2 to 8.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

preact is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Errors when using simulate() api

Hello! I'm trying to test the behaviour of a checkbox component.

    test('should call onChange callback when clicked', () => {
        const spy = jest.fn();

        const context = mount(<Checkbox name="foo" onChange={spy} />);

        context.find('input').simulate('change', { target: { value: true } });

        expect(spy).toHaveBeenCalledWith('foo', true);
    });

But calling the simulate api causes me multiple problems.

First I had this error:

ReferenceError: Event is not defined
at MountRenderer.Object.<anonymous>.MountRenderer.simulateEvent (node_modules/enzyme-adapter-preact-pure/build/src/MountRenderer.js:101:21)

which I resolved by putting Event in the global namespace in my setup file:

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

global.Event = window.Event;

But then I got another error:

TypeError: Cannot set property target of #<Event> which has only a getter
at MountRenderer.Object.<anonymous>.MountRenderer.simulateEvent (node_modules/enzyme-adapter-preact-pure/build/src/MountRenderer.js:106:16)

If I pass as arg a random key the error is not thrown but of course the test fail:

context.find('input').simulate('change', { foo: 'bar' });

For reference I'm using latest Preact (v10.0.0-beta.1) and latest enzyme-adapter-preact-pure (v1.13.1).

`suspenseFallback` option is not supported

When writing a test to validate my component is rendered, I see the fallback value.
here is component

import { h } from 'preact';
import { memo, Suspense } from 'preact/compat';

const Container = memo(({ component }) => (
    <Suspense fallback='loading'>
        {h(component, {})}
    </Suspense>
))

export default Container;

here is test

import { shallow, mount } from 'enzyme';
import { h } from 'preact';
import Container from '../src/components/container';
import { lazy } from 'preact/compat';

const LazyComponent = lazy(() => import('../src/components/lazy-component'));

describe('Container', () => {

    it('renders the LazyComponent', () => {
        const wrapper = mount(<Container component={LazyComponent} />, { suspenseFallback: false });
        console.log(wrapper.debug());
        expect(wrapper.find(LazyComponent).length).toEqual(1);
    });
})

here is result of the console.log

    <Memo() component={[Function: u]}>
      <Component component={[Function: u]}>
        <d fallback="loading">
          <d />
          loading
        </d>
      </Component>
    </Memo()>

as you can see there is not any of LazyComponent only fallback
here is repo with code
https://github.com/michael-vasyliv/preact-project

similar issue in enzymejs/enzyme#2200

Module '"enzyme"' has no exported ...

Hello,

after upgrading to typescript v5.2.2 I'm facing some issues with your package.
Screenshot 2023-09-25 at 11 49 57

I'm using:

  • "enzyme-adapter-preact-pure": "^4.1.0",
  • "@types/enzyme": "^3.10.14",

Can you please assist?

Move to enzyme org?

Since preact already has an org, it might not be practical to maintain access in a separate org, but I wanted to at least file the issue.

Now that enzyme is in its own github org (https://github.com/enzymejs), would you be interested in moving this adapter to that org? Of course permissions would remain the same, and yall would be able to add anyone to the org/github team you wanted.

Property 'createElement' in type 'Adapter' is not assignable to the same property in base type 'EnzymeAdapter'.

When trying to set up my Jest Preact tests like shown on the Preact website:

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-preact-pure";

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

an error is shown for the adapter parameter:

(property) adapter: Enzyme.EnzymeAdapter
Type 'Adapter' is not assignable to type 'EnzymeAdapter'.
  The types of 'createElement(...).type' are incompatible between these types.
    Type 'string | ComponentType<any>' is not assignable to type 'string | JSXElementConstructor<any>'.
      Type 'ComponentClass<any, {}>' is not assignable to type 'string | JSXElementConstructor<any>'.
        Type 'ComponentClass<any, {}>' is not assignable to type 'new (props: any) => Component<any, any, any>'.
          Construct signature return types 'Component<any, {}>' and 'Component<any, any, any>' are incompatible.
            The types returned by 'render(...)' are incompatible between these types.
              Type 'ComponentChild' is not assignable to type 'ReactNode'.
                Type 'bigint' is not assignable to type 'ReactNode'.ts(2322)
[index.d.ts(740, 5): ]()The expected type comes from property 'adapter' which is declared here on type '{ adapter: EnzymeAdapter; disableLifecycleMethods?: boolean | undefined; }'

When I look at the Adapter export I see indeed a difference in the definition of createElement (compared to EnzymeAdaptor ). EnzymeAdapter returns a ReactElement while enzyme-adapter-preact-pure returns a preact VNode.

Versions used:

preact: 10.7.1
enzyme-adapter-preact-pure: 3.4.0

Shallow rendering snapshot includes full html

First of all thank you for working on this enzyme adapter it has been very useful to me.

But I think I have discovered a bug: I have a component called Detail which renders a Title component like so:

<Title animal={data.animal} />

In the snapshot the following appears:

<Title
  animal={
    Object {
      "name": "Hank",
    }
  }
>
  <header
    className="header"
  >
    <h1>
      Hank
  </header>
</Title>

This is unexpected, since the h1 is part of the Title which I'm not shallow rendering.

The test:

/* @flow @jsx h */
import { h } from 'preact';
import { shallow } from 'enzyme';

import Detail from './Detail';

describe('Detail component', () => {
  let detail;

  describe('ui', () => {
    it('should know how to render occasions when everything goes right', () => {
      const detail = shallow(<Detail />);

      expect(detail).toMatchSnapshot();
    });
  });
});

The Detail component itself:

class Detail extends Component<Props, State> {
  render() {
    return (<Title animal={{name: "Hank"}} />);
   }
}

Run tests against preact/compat

Many users of Preact will be using the React compatibility module preact-compat (Preact v8) or preact/compat (Preact v10).

The tests should be run against these libraries to make sure the adapter works in projects that have {react, react-dom} => preact/compat aliases set up.

shallow renders which return `null` cannot have setState called on them

Tested in v2.2.1 and v3.0.0.

Example test case:

    it("renders", () => {
        class Tester extends React.Component {
            state = { show: false };
            render() {
                if (this.state.show) {
                    return <div>Hello</div>;
                }

                return null;
            }
        }

        const wrapper = shallow(<Tester />);
        expect(wrapper.find("div")).not.toExist();
        wrapper.setState({ show: true }); // throws Error: Method “setState” is meant to be run on 1 node. 0 found instead.
        expect(wrapper.find("div")).toExist();
    });

When working with the React v15 adapter, wrapper is a ShallowWrapper with a length of one, where the single value is a null. This allows me to call setState and update it. Using enzyme-adapter-preact-pure, wrapper has a length of zero, with no elements associated with it.

Error with Preact 10 and arrow-function components

Hi,

If I mount a Class component the tests work fine, but when I try a functional component (stateless in this case) I get the following error

TypeError: Cannot read property 'render' of undefined

When I run this code

mount(<Input name="input-name" type="text" />)

And my component is defined with

const Input = (props: Props) => {
    return (
        <div> //....

I'm using preact 10 with typescript, it's the first time that I use enzyme so maybe I'm doing something wrong. I also have this configuration that is called at the

import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';
configure({ adapter: new Adapter() });

export { mount };

The mount that I use on my test is the mount that gets exported.

ReferenceError: h is not defined

Getting this error and trying to execute your example code provided in the repo. I get the h is not defined error. My test is just normal js file

import { mount } from 'enzyme';

const wrapper = mount(<div class="widget"/>);
wrapper.props() // Returns `{ children: [], className: 'widget' }`
wrapper.find('.widget').length // Returns `1`

I have this in my babelrc as well which is supposed to help with this issue:

{
    "plugins": [
      [
        "transform-react-jsx",
        {
          "pragma": "h"
        }
      ]
    ]
  }
 ReferenceError: h is not defined

       9 | // })
      10 |
    > 11 | const wrapper = mount(<div class="widget"/>);
         |                           ^
      12 | wrapper.props() // Returns `{ children: [], className: 'widget' }`
      13 | wrapper.find('.widget').length // Returns `1`
      14 |

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.