Skip to content

Commit

Permalink
Merge pull request #135 from preactjs/wrap-invoke-support
Browse files Browse the repository at this point in the history
Support `invoke` API
  • Loading branch information
robertknight committed Apr 8, 2021
2 parents d268dd5 + a27b4c8 commit 682b042
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/MountRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,12 @@ export default class MountRenderer implements AbstractMountRenderer {
container() {
return this._container;
}

wrapInvoke(callback: () => any) {
let result;
act(() => {
result = callback();
});
return result;
}
}
12 changes: 12 additions & 0 deletions test/MountRenderer_test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,16 @@ describe('MountRenderer', () => {
});
});
});

describe('#wrapInvoke', () => {
it('returns result of callback', () => {
const Widget = () => <div />;
const renderer = new MountRenderer();
renderer.render(<Widget />);

const result = renderer.wrapInvoke(() => 'test');

assert.equal(result, 'test');
});
});
});
23 changes: 23 additions & 0 deletions test/integration_test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from 'enzyme';
import { Component, Fragment, options } from './preact';
import * as preact from 'preact';
import { useEffect, useState } from 'preact/hooks';
import { ReactElement } from 'react';

import { assert } from 'chai';
Expand Down Expand Up @@ -401,6 +402,28 @@ describe('integration tests', () => {
assert.ok(container.querySelector('button'));
wrapper.detach();
});

it('flushes effects and state updates when using `invoke`', () => {
let effectCount = 0;

const Child = ({ children, onClick }: any) => (
<button onClick={onClick}>{children}</button>
);
const Parent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
effectCount = count;
}, [count]);
return <Child onClick={() => setCount(c => c + 1)}>{count}</Child>;
};

const wrapper = mount(<Parent />);
// @ts-ignore - `onClick` type is wrong
wrapper.find('Child').invoke('onClick')();

assert.equal(wrapper.text(), '1');
assert.equal(effectCount, 1);
});
});

describe('"shallow" rendering', () => {
Expand Down

0 comments on commit 682b042

Please sign in to comment.