beforeEach(done => {
   next = expect.createSpy().andCall(() => done());
   logicA = createLogic({
     type: 'FOO',
     validate({ action }, allow, reject) {
       if (action.allowMe) {
         allow({
             ...action,
           allowed: ['a']
         });
       } else {
         reject(action);
       }
     }
   });
   mw = createLogicMiddleware([logicA]);
   mw({})(next)(actionAllow);
 });
Example #2
0
function setup({ active, text }) {
  const actions = {
    onClick: expect.createSpy()
  }

  const component = shallow(
    <Link active={active} {...actions}>
      {text}
    </Link>
  )

  return {
    component: component,
    actions: actions,
    a: component.find('a'),
    span: component.find('span')
  }
}
	const setup = (options, inputHtml = '<input type="text"/>') => {
		testContainer.empty();

		ifp = $(inputHtml).appendTo(testContainer);

		ifw = Object.create(def);
		ifw._trigger = expect.createSpy();
		ifw.element = ifp;
		ifw.options = options || ifw.options;

		ifw._create();

		spy = {
			_clean: expect.spyOn(ifw, '_clean'),
			_type: expect.spyOn(ifw, '_type').andCallThrough(),
			trigger: expect.spyOn(ifp, 'trigger').andCallThrough()
		};
	};
Example #4
0
  it('should unsubscribe a listener', () => {
    const changeListenerSpy = expect.createSpy(() => {});
    const unsubscribe = redux.subscribe(changeListenerSpy);

    expect(changeListenerSpy.calls.length).toBe(0);

    redux.dispatch(addTodo('Hello'));
    expect(redux.getState().todoStore).toEqual([{ id: 1, text: 'Hello'}]);
    expect(changeListenerSpy.calls.length).toBe(1);

    unsubscribe();
    redux.dispatch(addTodo('World'));
    expect(redux.getState().todoStore).toEqual([
      { id: 2, text: 'World'},
      { id: 1, text: 'Hello'}
    ]);
    expect(changeListenerSpy.calls.length).toBe(1);
  });
    it('should call function provided for onMouseOver', () => {

      const list = [{ name : 'test', id : 100 }, { name : 'test2', id : 101 }]
      const click = expect.createSpy()
      const wrapper = shallow(<RecipeList {...minProps} list={list} toggleHighlight={click} />)

      let recipes = wrapper.find('.recipeItem')
      
      expect(click.calls.length).toBe(0)
      
      recipes.at(1).simulate('mouseOver')
      expect(click.calls.length).toBe(1)
      expect(click.calls[0].arguments[0]).toBe(101)

      recipes.at(0).simulate('mouseOver')
      expect(click.calls.length).toBe(2)
      expect(click.calls[1].arguments[0]).toBe(100)
    })
  it('should be able to press buttons for new idea', () => {
    const props = {
      index: 0,
      rowIDDisplay: 1,
      idea: {
        title: 'My idea'
      },
      state: {
        ideas: [ { title: 'My idea' }]
      },
      onSelect: expect.createSpy()
    };
    const { output } = setup(IdeaCell, props);

    const button = output.props.children[2];
    button.props.onPress();
    expect(props.onSelect.calls.length).toBe(1);
  });
Example #7
0
function setup() {
  const props = {
    recipeSearch: '', 
		findRecipe: () => {},
    handleRecipeSearch: expect.createSpy(),
  }; 
  const wrapper = shallow(
    <Form {...props} />
  );
	const testWrapper = mount(
		<Form {...props} onChange={props.handleRecipeSearch} />
	)
  return {
		props,
    wrapper,
		testWrapper
  }
};
Example #8
0
function setup(propOverrides) {
    const props = Object.assign({}, {
        round : 0,
        restart : expect.createSpy()
    }, propOverrides);

    const renderer = TestUtils.createRenderer()

    renderer.render(<Header {...props} />)

    let output = renderer.getRenderOutput()

    return {
        props: props,
        output: output,
        renderer: renderer
    }
}
const render = (total, products = []) => {
    const actions = {
        onCheckoutClicked: expect.createSpy(),
    }

    const component = mount(
        <Cart total={total} products={products} {...actions} />
    )

    return {
        component,
        actions,
        p: component.find('p'),
        em: component.find('em'),
        button: component.find('button'),
        products: component.find(Product),
    }
}
  it('maps onChange properly', () => {
    const onChange = createSpy()
    const first = new Date('2016-01-01')
    const second = new Date('2016-02-29')

    const dom = TestUtils.renderIntoDocument(
        <MuiThemeProvider muiTheme={getMuiTheme()}>
          <ReduxFormMaterialUIDatePicker input={{ name: 'myDatePicker', onChange, value: first }}/>
        </MuiThemeProvider>
      )

    const datePicker = TestUtils.findRenderedComponentWithType(dom, DatePicker)
    expect(onChange).toNotHaveBeenCalled()
    datePicker.props.onChange(undefined, second)
    expect(onChange)
      .toHaveBeenCalled()
      .toHaveBeenCalledWith(second)
  })
Example #11
0
describe("<Models/>", function(){
  // Given
  let components = {
    Collapse: ModelCollpase,
    ModelWrapper: ModelComponent
  }
  let props = {
    getComponent: (c) => {
        return components[c]
    },
    specSelectors: {
      isOAS3: () => false,
      definitions: function() {
        return fromJS({
          def1: {},
          def2: {}
        })
      },
      specResolvedSubtree: () => {}
    },
    layoutSelectors: {
      isShown: createSpy()
    },
    layoutActions: {},
    getConfigs: () => ({
      docExpansion: "list",
      defaultModelsExpandDepth: 0
    })
  }


  it("passes defaultModelsExpandDepth to ModelWrapper", function(){
    // When
    let wrapper = shallow(<Models {...props}/>)

    // Then should render tabs
    expect(wrapper.find("ModelCollapse").length).toEqual(1)
    expect(wrapper.find("ModelWrapper").length).toBeGreaterThan(0)
    wrapper.find("ModelComponent").forEach((modelWrapper) => {
      expect(modelWrapper.props().expandDepth).toBe(0)
    })
  })

})
Example #12
0
 it('should have value set to initial value on first render', () => {
   const store = makeStore({})
   const input = createSpy(props => <input {...props.input}/>).andCallThrough()
   class Form extends Component {
     render() {
       return <div><Field name="foo" component={input}/></div>
     }
   }
   const TestForm = reduxForm({
     form: 'testForm'
   })(Form)
   TestUtils.renderIntoDocument(
     <Provider store={store}>
       <TestForm initialValues={{ foo: 'bar' }}/>
     </Provider>
   )
   expect(input).toHaveBeenCalled()
   expect(input.calls[ 0 ].arguments[ 0 ].input.value).toBe('bar')
 })
Example #13
0
  it('destroy modal state before unmount', () => {
    const mockReducer = createSpy().andReturn({})
    const finalReducer = combineReducers({ modal: mockReducer })
    const store = createStore(finalReducer)

    const wrapper = mount(
      <ProviderMock store={store}>
        <WrappedMyModal />
      </ProviderMock>
    )

    wrapper.unmount()

    const calls = mockReducer.calls
    expect(calls[calls.length - 1].arguments).toEqual([
      {},
      destroy('myModal')
    ])
  })
Example #14
0
    it('should call the correct action handler', function() {
      var action = {type: ActionTypes.ACTION_ONE, data: {hello: 'universe'}};
      var actionHandler = expect.createSpy();
      var reducer = createReducer(initialState, {
        name: '',
        handlers: {
          onActionOne: [ActionTypes.ACTION_ONE]
        },
        onActionOne: actionHandler
      });

      // Simulates an action firing and the reducer executing
      reducer(undefined, action);

      // The correct action handler function should have fired
      // with the right arguments
      expect(actionHandler.calls.length).toBe(1);
      expect(actionHandler).toHaveBeenCalledWith(initialState, action.data);
    });
function setup(newProps) {
  const props = {
    label: 'elegonza',
    value: 'realness',
    placeholder: 'hunti',
    className: 'testing',
    handleChange: expect.createSpy(),
    id: 'unique',
    type: 'text',
    ...newProps,
  };

  const wrapper = shallow(<Input {...props} />);

  return {
    wrapper,
    props,
  };
}
Example #16
0
    it('should output a <form> element with all props mapped', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy()
      class TestForm extends Component {
        render() {
          return (
            <Form
              onSubmit={onSubmit}
              action="/save"
              method="post"
              target="_blank"
              rel="noopener noreferrer"
            >
              <Field name="foo" component="input" />
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm />
        </Provider>
      )

      expect(onSubmit).toNotHaveBeenCalled()

      const tag = TestUtils.findRenderedDOMComponentWithTag(dom, 'form')

      // 🤢 This line is DISGUSTING!! Is there a better way to get the props on the <form> ??
      const props = tag[Object.keys(tag)[0]]._currentElement.props

      expect(props.onSubmit).toBe(onSubmit)
      expect(props.action).toBe('/save')
      expect(props.method).toBe('post')
      expect(props.target).toBe('_blank')
    })
Example #17
0
const setup = () => {
  const props = {
    lemma: 'lemma',
    position: 5,
    part: 'part',
    record: {
      meaning: 'meaning'
    },
    onChange: expect.createSpy()
  }
  const component = shallow(<Record {...props} />)
  return {
    lemma: component.find('h1').text(),
    position: component.find('dd').at(0).text(),
    part: component.find('dd').at(1).text(),
    meaning: component.find('#meaning'),
    onChange: props.onChange
  }
}
 it('should provide map', () => {
   const callback = createSpy(name => ({ whatever: true, name })).andCallThrough()
   const result = createFieldArrayProps(...defaultParams, {
     value: fromJS([ 'a', 'b', 'c' ]),
     length: 3
   })
   expect(result.fields.map).toBeA('function')
   expect(callback).toNotHaveBeenCalled()
   const mapResult = result.fields.map(callback)
   expect(size(mapResult), 3)
   expect(getIn(mapResult, 0)).toEqual({ whatever: true, name: 'foo[0]' })
   expect(getIn(mapResult, 1)).toEqual({ whatever: true, name: 'foo[1]' })
   expect(getIn(mapResult, 2)).toEqual({ whatever: true, name: 'foo[2]' })
   expect(callback).toHaveBeenCalled()
   expect(callback.calls.length).toBe(3)
   expect(callback.calls[ 0 ].arguments).toEqual([ 'foo[0]', 0, result.fields ])
   expect(callback.calls[ 1 ].arguments).toEqual([ 'foo[1]', 1, result.fields ])
   expect(callback.calls[ 2 ].arguments).toEqual([ 'foo[2]', 2, result.fields ])
 })
test("map props on window's scroll event", () => {
  const mapSpy = expect.createSpy().andReturn({ foo: "bar" });

  const Container = mapPropsOnScroll(mapSpy, f => f)(Null);

  const wrapper = mount(<Container />);

  simulant.fire(window, "scroll");
  expect(mapSpy.calls.length).toEqual(1);
  expect(wrapper.find(Null).instance().props).toEqual({ foo: "bar" });

  simulant.fire(window, "scroll");
  expect(mapSpy.calls.length).toEqual(2);

  wrapper.unmount();

  simulant.fire(window, "scroll");
  expect(mapSpy.calls.length).toEqual(2);
});
Example #20
0
  it('should link to /features', () => {
    const openRouteSpy = expect.createSpy();

    // Spy on the openRoute method of the HomePage
    const openRoute = (dest) => {
      if (dest === '/features') {
        openRouteSpy();
      }
    };

    const renderedComponent = mount(
      <IntlProvider locale="en">
        <HomePage loading changeRoute={openRoute} />
      </IntlProvider>
    );
    const button = renderedComponent.find('button');
    button.simulate('click');
    expect(openRouteSpy).toHaveBeenCalled();
  });
Example #21
0
    it('should rerender when sync error is cleared', () => {
      const store = makeStore()
      const usernameInput = createSpy(props => <input {...props.input}/>).andCallThrough()
      const validate = values => {
        const username = getIn(values, 'username')
        return username ? {} : { username: '******' }
      }
      class Form extends Component {
        render() {
          return (<div>
            <Fields names={[ 'username' ]} component={usernameInput}/>
          </div>)
        }
      }
      const TestForm = reduxForm({
        form: 'testForm',
        validate
      })(Form)
      TestUtils.renderIntoDocument(
        <Provider store={store}>
          <TestForm/>
        </Provider>
      )

      // username input rendered
      expect(usernameInput).toHaveBeenCalled()
      expect(usernameInput.calls.length).toBe(1)

      // username field has error
      expect(usernameInput.calls[ 0 ].arguments[ 0 ].username.meta.valid).toBe(false)
      expect(usernameInput.calls[ 0 ].arguments[ 0 ].username.meta.error).toBe('Required')

      // update username field so it passes
      usernameInput.calls[ 0 ].arguments[ 0 ].username.input.onChange('erikras')

      // username input rerendered
      expect(usernameInput.calls.length).toBe(2)

      // should be valid now
      expect(usernameInput.calls[ 1 ].arguments[ 0 ].username.meta.valid).toBe(true)
      expect(usernameInput.calls[ 1 ].arguments[ 0 ].username.meta.error).toBe(undefined)
    })
Example #22
0
    it('should provide valid/invalid/values getters', function () {
      var store = makeStore({});
      var input = createSpy(function (props) {
        return React.createElement('input', props);
      }).andCallThrough();

      var Form = function Form() {
        return React.createElement(
          'form',
          null,
          React.createElement(Field, { name: 'bar', component: input, type: 'text' })
        );
      };

      var Decorated = reduxForm({
        form: 'testForm',
        validate: function validate(values) {
          return getIn(values, 'bar') ? {} : { bar: 'Required' };
        }
      })(Form);

      var dom = TestUtils.renderIntoDocument(React.createElement(
        Provider,
        { store: store },
        React.createElement(Decorated, null)
      ));

      var stub = TestUtils.findRenderedComponentWithType(dom, Decorated);

      // invalid because no value for 'bar' field
      expect(stub.valid).toBe(false);
      expect(stub.invalid).toBe(true);
      expect(stub.values).toEqualMap({});

      // set value for 'bar' field
      input.calls[0].arguments[0].onChange('foo');

      // valid because we have a value for 'bar' field
      expect(stub.valid).toBe(true);
      expect(stub.invalid).toBe(false);
      expect(stub.values).toEqualMap({ bar: 'foo' });
    });
 it('should provide reduce', () => {
   const callback = createSpy((accumulator, name) => ({
     ...accumulator,
     [name]: { whatever: true, name }
   })).andCallThrough()
   const result = createFieldArrayProps(...defaultParams, {
     value: fromJS(['a', 'b', 'c']),
     length: 3
   })
   expect(result.fields.reduce).toBeA('function')
   expect(callback).toNotHaveBeenCalled()
   const reduceResult = result.fields.reduce(callback, {})
   expect(size(reduceResult), 3)
   expect(reduceResult['foo[0]']).toEqual({ whatever: true, name: 'foo[0]' })
   expect(reduceResult['foo[1]']).toEqual({ whatever: true, name: 'foo[1]' })
   expect(reduceResult['foo[2]']).toEqual({ whatever: true, name: 'foo[2]' })
   expect(callback).toHaveBeenCalled()
   expect(callback.calls.length).toBe(3)
   expect(callback.calls[0].arguments).toEqual([
     {},
     'foo[0]',
     0,
     result.fields
   ])
   expect(callback.calls[1].arguments).toEqual([
     {
       'foo[0]': { whatever: true, name: 'foo[0]' }
     },
     'foo[1]',
     1,
     result.fields
   ])
   expect(callback.calls[2].arguments).toEqual([
     {
       'foo[0]': { whatever: true, name: 'foo[0]' },
       'foo[1]': { whatever: true, name: 'foo[1]' }
     },
     'foo[2]',
     2,
     result.fields
   ])
 })
    beforeEach( (asyncDone) => {
      // mock out our api
      const api = {
        items: {
          retrieveItemDetail(itemTypeParam, itemNumParam, logParam) {
            expect(itemTypeParam).toBe(itemType);
            expect(itemNumParam).toBe(itemNum);
            return new Promise((resolve, reject) => {
              reject(testErr);
            });
          }
        }
      };

      // monitor our dispatch invocations
      dispatch = expect.createSpy().andCall(() => asyncDone());

      // invoke our logic module under test
      processDetailItemAction.process( {action, api}, dispatch);
    });
function setup( propOverrides ) {
	const props = Object.assign({
		href: '',
		text: '',
		className: '',
		onClick:  expect.createSpy()
	},  propOverrides)

	let renderer = TestUtils.createRenderer()
	renderer.render(<Link {...props} />)
	let output = renderer.getRenderOutput()
	let instance = renderer.getMountedInstance()

	return {
		props,
		output,
		renderer,
		instance
	}
}
Example #26
0
  it('pass handleHide to the given component', () => {
    const initialState = { myModal: { props: {}, show: true } }
    const mockReducer = createSpy().andReturn(initialState)
    const finalReducer = combineReducers({ modal: mockReducer })
    const store = createStore(finalReducer)

    const wrapper = mount(
      <ProviderMock store={store}>
        <WrappedMyModal />
      </ProviderMock>
    )

    wrapper.find(MyModal).props().handleHide()

    const calls = mockReducer.calls
    expect(calls[calls.length - 1].arguments).toEqual([
      initialState,
      hide('myModal')
    ])
  })
Example #27
0
  it('should support withRef', function () {
    const spy = expect.createSpy()

    class MyComponent extends Component {
      invokeSpy() {
        spy()
      }

      render() {
        return null
      }
    }

    const WrappedComponent = withRouter(MyComponent, { withRef: true })

    const instance = render(<WrappedComponent router={routerStub} />, node)
    instance.getWrappedInstance().invokeSpy()

    expect(spy).toHaveBeenCalled()
  })
Example #28
0
    it('should submit when submit() called and onSubmit provided as config param', function () {
      var store = makeStore({
        testForm: {
          values: {
            bar: 'foo'
          }
        }
      });
      var input = createSpy(function (props) {
        return React.createElement('input', props);
      }).andCallThrough();

      var Form = function Form() {
        return React.createElement(
          'form',
          null,
          React.createElement(Field, { name: 'bar', component: input, type: 'text' })
        );
      };

      var Decorated = reduxForm({
        form: 'testForm',
        onSubmit: function onSubmit(values) {
          expect(values).toEqualMap({ bar: 'foo' });
        }
      })(Form);

      var dom = TestUtils.renderIntoDocument(React.createElement(
        Provider,
        { store: store },
        React.createElement(Decorated, null)
      ));

      var stub = TestUtils.findRenderedComponentWithType(dom, Decorated);

      expect(input).toHaveBeenCalled();
      expect(input.calls[0].arguments[0].value).toBe('foo');

      expect(stub.submit).toBeA('function');
      stub.submit();
    });
Example #29
0
    it('should call the onSubmit given to <Form> when instance API submit() is called', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy().andReturn(7)
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input" />
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm />
        </Provider>
      )

      const decoratedForm = TestUtils.findRenderedComponentWithType(
        dom,
        DecoratedTestForm
      )

      expect(onSubmit).toNotHaveBeenCalled()

      const result = decoratedForm.submit()
      expect(result).toBe(7)

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })
    })
Example #30
0
function createSpyProps(store) {
  const props = {
    dispatch: store.dispatch,
    page: new Page(),
    userTypedLocation: '',
    showCompletions: true,
    profile: new Profile(),
    onLocationChange: expect.createSpy(),
    onLocationContextMenu: expect.createSpy(),
    onLocationReset: expect.createSpy(),
    isBookmarked: expect.createSpy(),
    bookmark: expect.createSpy(),
    unbookmark: expect.createSpy(),
    ipcRenderer: Object.create(null),
    navigateTo: expect.createSpy(),
  };
  props.pages = [props.page];
  return props;
}