all files / src/__tests__/ asyncValidation.spec.js

98.28% Statements 57/58
100% Branches 4/4
80% Functions 16/20
100% Lines 44/44
3 statements Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                              
import expect, {createSpy} from 'expect';
import isPromise from 'is-promise';
import asyncValidation from '../asyncValidation';
 
describe('asyncValidation', () => {
  const field = 'myField';
 
  it('should throw an error if fn does not return a promise', () => {
    const fn = () => null;
    const start = () => null;
    const stop = () => null;
    expect(() => asyncValidation(fn, start, stop, field))
      .toThrow(/promise/);
  });
 
  it('should return a promise', () => {
    const fn = () => Promise.resolve();
    const start = () => null;
    const stop = () => null;
    expect(isPromise(asyncValidation(fn, start, stop, field))).toBe(true);
  });
 
  it('should call start, fn, and stop on promise resolve', () => {
    const fn = createSpy().andReturn(Promise.resolve());
    const start = createSpy();
    const stop = createSpy();
    const promise = asyncValidation(fn, start, stop, field);
    expect(fn).toHaveBeenCalled();
    expect(start)
      .toHaveBeenCalled()
      .toHaveBeenCalledWith(field);
    return promise.then(() => {
      expect(stop).toHaveBeenCalled();
    }, () => {
      expect(false).toBe(true); // should not get into reject branch
    });
  });
 
  it('should throw when promise rejected with no errors', () => {
    const fn = createSpy().andReturn(Promise.reject());
    const start = createSpy();
    const stop = createSpy();
    const promise = asyncValidation(fn, start, stop, field);
    expect(fn).toHaveBeenCalled();
    expect(start)
      .toHaveBeenCalled()
      .toHaveBeenCalledWith(field);
    return promise.then(() => {
      expect(false).toBe(true); // should not get into resolve branch
    }, () => {
      expect(stop).toHaveBeenCalled();
    });
  });
 
  it('should call start, fn, and stop on promise reject', () => {
    const errors = {foo: 'error'};
    const fn = createSpy().andReturn(Promise.reject(errors));
    const start = createSpy();
    const stop = createSpy();
    const promise = asyncValidation(fn, start, stop, field);
    expect(fn).toHaveBeenCalled();
    expect(start)
      .toHaveBeenCalled()
      .toHaveBeenCalledWith(field);
    return promise.then(() => {
      expect(false).toBe(true); // should not get into resolve branch
    }, () => {
      expect(stop)
        .toHaveBeenCalled()
        .toHaveBeenCalledWith(errors);
    });
  });
});