Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added reduce() function for FindWrapper #63

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export interface FindWrapper<P, S> {
**/
find<Q, T>(selector: string): FindWrapper<Q, T>;

/**
* Applies provided function to every element, returning a single value.
**/
reduce<T>(fn: (prevVal: T, wrapper: this, index: number) => T, initialValue: T): T;

/** Requires a single `Component` or functional node. Returns the raw vdom output of the given component. */
output(): preact.VNode;

Expand Down Expand Up @@ -84,4 +89,4 @@ interface ShallowFunction {
export const deep: DeepFunction;
export const render: DeepFunction;
export const shallow: ShallowFunction;
export default deep;
export default deep;
11 changes: 11 additions & 0 deletions src/preact-render-spy.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,17 @@ class FindWrapper {
);
}

reduce(fn, initialValue) {
verifyFoundNodes(this);
if (initialValue === undefined) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the typeof check.

typeof initialValue === 'undefined'

throw new Error('preact-render-spy: reduce initialValue is missing');
}
return Array.from(this).reduce(
(accumulator, vnode, index) => fn(accumulator, new FindWrapper(this.context, [vnode]), index),
initialValue
);
}

component() {
if (this.length !== 1) {
throw new Error('preact-render-spy: component method can only be used on a single node');
Expand Down
6 changes: 6 additions & 0 deletions src/shared-render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ const sharedTests = (name, func) => {
expect(context.filter(<span />).length).toBe(0);
});

it(`${name}: reduce components`, () => {
const context = func(<div><NullStateless class="first" value={1} /><NullStateless value={2} /></div>);
expect(context.find('NullStateless').reduce((sum, n) => sum + n.attr('value'), 1)).toEqual(4);
expect(() => context.find('NullStateless').reduce((sum, n) => sum + n.attr('value'))).toThrow();
});

it(`${name}: output returns vdom output by a Component`, () => {
const context = func(<DivChildren><span /></DivChildren>);
expect(() => context.find('div').output()).toThrow();
Expand Down