Example #1
0
 it('getRowData should log errors', () => {
   fetchMock.restore();
   let mockError = new Error('intentional habitDetails.spec error for testing');
   fetchMock.get(/\/habits/, { throws: mockError });
   fullDetailsWrapper.node.getRowData();
   fetchMock.restore();
   fetchMock.get(/\/habits/, { body: [] });
 });
Example #2
0
 beforeEach(() => {
   fetchMock.get(
     getProjectUrl('/jobs/?count=2'),
     paginatedJobListFixtureOne,
   );
   fetchMock.get(
     getProjectUrl('/jobs/?count=2&offset=2'),
     paginatedJobListFixtureTwo,
   );
 });
 it("returns parsedReplicationDocs", () => {
   fetchMock.getOnce('./_scheduler/jobs', 200);
   fetchMock.get('./_replicator/_all_docs?include_docs=true&limit=100', _repDocs);
   fetchMock.get('./_scheduler/docs?include_docs=true', _schedDocs);
   return supportNewApi(true)
     .then(fetchReplicationDocs)
     .then(docs => {
       assert.deepEqual(docs.length, 1);
       assert.deepEqual(docs[0]._id, "c94d4839d1897105cb75e1251e0003ea");
       assert.deepEqual(docs[0].stateTime.toDateString(), (new Date('2017-03-07T14:46:17')).toDateString());
     });
 });
  it('should NOT do request if data exists and maxAge is -1', function () {
    this.dataManager.setStateForKey({
      byId: {
        '1': {
          isFetching: false,
          fetchDate: new Date(),
          data: {
            id: 1,
            hi: 1,
            guid: 'guid-1',
            something: 'before',
          },
        },
      },
    }, '/model');


    fetchMock.get('/model/1', { id: 1, name: 'hi' });
    showAction(this.dataManager, {
      path: '/model',
      id: 1,
      maxAge: -1,
    });
    expect(fetchMock.called('/model/1')).toEqual(false);
  });
Example #5
0
export default function setupSupersetClient() {
  // The following is needed to mock out SupersetClient requests
  // including CSRF authentication and initialization
  global.FormData = window.FormData; // used by SupersetClient
  fetchMock.get('glob:*superset/csrf_token/*', { csrf_token: '1234' });
  SupersetClient.configure({ protocol: 'http', host: 'localhost' }).init();
}
Example #6
0
  test('getFile unencrypted', (t) => {
    t.plan(2)

    const path = 'file.json'
    const gaiaHubConfig = {
      address: '1NZNxhoxobqwsNvTb16pdeiqvFvce3Yg8U',
      server: 'https://hub.blockstack.org',
      token: '',
      url_prefix: 'gaia.testblockstack.org/hub/'
    }

    const fullReadUrl = 'https://gaia.testblockstack.org/hub/1NZNxhoxobqwsNvTb16pdeiqvFvce3Yg8U/file.json'
    const fileContent = { test: 'test' }

    const getOrSetLocalGaiaHubConnection = sinon.stub().resolves(gaiaHubConfig)
    const getFullReadUrl = sinon.stub().resolves(fullReadUrl)

    const { getFile } = proxyquire('../../../lib/storage', {
      './hub': { getOrSetLocalGaiaHubConnection, getFullReadUrl },
    })

    FetchMock.get(fullReadUrl, fileContent)

    getFile(path)
      .then((file) => {
        t.ok(file, 'Returns file content')
        t.same(JSON.parse(file), fileContent)
      })
  })
Example #7
0
  test('connectToGaiaHub', (t) => {
    t.plan(5)

    const hubServer = 'hub.testblockstack.org'

    const hubInfo = {
      read_url_prefix: 'gaia.testblockstack.org',
      challenge_text: 'please-sign',
    }

    const privateKey = 'a5c61c6ca7b3e7e55edee68566aeab22e4da26baa285c7bd10e8d2218aa3b229'
    const address = '1NZNxhoxobqwsNvTb16pdeiqvFvce3Yg8U'
    const publicKey = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'

    FetchMock.get(`${hubServer}/hub_info`,
                   JSON.stringify(hubInfo))

    connectToGaiaHub(hubServer, privateKey)
      .then((config) => {
        t.ok(config, 'Config returned by connectToGaiaHub()')
        t.equal(hubInfo.read_url_prefix, config.url_prefix)
        t.equal(address, config.address)
        t.equal(hubServer, config.server)

        const verificationKey = bitcoin.ECPair.fromPublicKeyBuffer(Buffer.from(publicKey, 'hex'))

        const decoded = JSON.parse(Buffer.from(config.token, 'base64').toString())
        const signature = bitcoin.ECSignature.fromDER(Buffer.from(
          decoded.signature, 'hex'))

        t.ok(verificationKey.verify(
          bitcoin.crypto.sha256(hubInfo.challenge_text), signature), 'Verified token')
      })
  })
Example #8
0
    it('dispatches LOGIN_SUCCESS when login successful', (done) => {
      const fakeUser = {
        userId: 'userId1',
        twitterId: 'twitterId1',
        username: '******',
        isAuthenticated: true
      };

      fetchMock
        .get(`${rootUrl}/auth/verify`, {
          status: 200,
          body: {
            data: Object.assign({}, fakeUser)
          }
        });

      const expectedActions = [
        { type: actionTypes.LOGIN },
        { type: actionTypes.LOGIN_SUCCESS, payload: { user: fakeUser } }
      ];

      const store = mockStore(initialState);
      store.dispatch(actions.loginUser())
        .then(() => {
          expect(store.getActions()).to.deep.equal(expectedActions);
          done();
        });
    });
    it('checks for RATE_LIMIT_EXCEEDED', function(done) {
      const store = storeWithPolling();
      let poller = null;
      fetchMock.get(pollUrl, {
        status: 400,
        body: '{"error":"Too many requests"}',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      let state = store.getState();
      const interval = state.polling.get('interval');

      let success = false;
      store.subscribe(() => {
        state = store.getState();
        if (state.polling.get('interval') > interval) {
          success = true;
          fetchMock.restore();
          poller.stop();
          done();
        }
      });

      poller = handlePolling(store);

      setTimeout(() => {
        if (!success) {
          fetchMock.restore();
          poller.stop();
          done(new Error("RATE_LIMIT_EXCEEDED wasn't detected"));
        }
      }, 50);
    });
    it("doesn't assign work if the worker isn't ready", function(done) {
      const workUrl = 'http://work.com';
      const store = storeWithPolling();
      fetchMock.get(pollUrl, () => {
        store.dispatch(updateWorkerState('inactive'));
        return { work_available: true, url: workUrl };
      });

      let err = false;
      store.subscribe(() => {
        const { worker } = store.getState();
        if (worker.get('error')) {
          err = true;
          done(worker.get('error'));
        }
      });

      handlePolling(store);

      setTimeout(() => {
        if (!err) {
          done();
        }
      }, 50);
    });
    it("doesn't poll", function(done) {
      const store = createStore(pluginApp);
      store.dispatch(setPollingInterval(1));
      store.dispatch(updateWorkerState('ready'));
      store.dispatch(stopPolling());
      let fail = false;
      let poller = null;

      fetchMock.get(pollUrl, () => {
        poller.stop();
        fetchMock.restore();
        fail = true;

        done(new Error("Shouldn't have polled because polling is off!"));
      });

      poller = handlePolling(store);
      setTimeout(() => {
        if (!fail) {
          fetchMock.restore();
          poller.stop();
          done();
        }
      }, 10);
    });
    it('checks for CAPTCHAs', function(done) {
      const store = storeWithPolling();
      let poller = null;
      fetchMock.get(pollUrl, {
        status: 503,
        body: '<html>CAPTCHA nonsense!</html>',
        headers: {
          'Content-Type': 'text/html',
        },
      });

      let success = false;
      store.subscribe(() => {
        const state = store.getState();
        if (state.polling.get('captchaRequired')) {
          success = true;
          fetchMock.restore();
          poller.stop();
          done();
        }
      });

      poller = handlePolling(store);

      setTimeout(() => {
        if (!success) {
          fetchMock.restore();
          poller.stop();
          done(new Error("CAPTCHA wasn't detected"));
        }
      }, 50);
    });
Example #13
0
 before(() => {
   let mockHabit = {
     action: 'foobar',
     lastDone: Date.now(),
     streak: {
       max: 3,
       current: 1,
       instanceCount: 2,
     },
   };
   fetchMock.get(/\/habits/, {
     body: [
       {
         _id: '1',
         createdAt: Date.now(),
         note: 'foo',
         updatedAt: Date.now(),
       },
       {
         _id: '2',
         createdAt: Date.now(),
         note: 'bar',
         updatedAt: Date.now(),
       }
     ],
   });
   fullDetailsWrapper = mount(
     <HabitDetails
       token={{}}
       profile={{}}
       habit={mockHabit}
       navigator={{ push: function() {} }}
     />
   );
 });
 it('creates an async action to fetch the bitcoin value', () => {
   fetchMock.get('https://api.coindesk.com/v1/bpi/currentprice.json',mockResponse)
   const expectedActions = [{payload:mockResponse.body, type:FETCH_BITCOIN}];
   return store.dispatch(fetchBitcoin())
   .then(() => {
     expect(store.getActions()).toEqual(expectedActions)
   })
 })
 beforeEach(() => {
     fetchMock.get('*', { hello: 'world' });
     store = {
         dispatch: sinon.stub()
         , getState: sinon.stub()
     };
     store.dispatch.returnsArg(0);
 });
Example #16
0
 beforeEach(() => {
   fetchMock.get({
     matcher: matcherName,
     response: {
       status: 404,
     },
   });
 });
Example #17
0
		it('should throw an error', function (done) {
			fetchMock.get('/api/components/names', {});

			tcomp.Datastores().catch(function (err) {
				expect(err).toBeDefined();
				done();
			});
		});
 it('should do GET request to /models for index', function () {
   fetchMock.get('/model', [{ id: 1, name: 'hi' }]);
   const state = indexAction(this.dataManager, {
     path: '/model',
   });
   expect(state.isFetching).toEqual(true);
   expect(fetchMock.called('/model')).toEqual(true);
 });
 it('creates an async action to fetch the litecoin value', () => {
   fetchMock.get('https://api.coinmarketcap.com/v1/ticker/',mockResponse)
   const expectedActions = [{payload:mockResponse.body, type:FETCH_LITECOIN}];
   return store.dispatch(fetchLiteCoin())
   .then(() => {
     expect(store.getActions()).toEqual(expectedActions)
   })
 })
Example #20
0
 before(() => {
   fetchMock.get(/\/stroke/, {
     status: 200,
     body: _strokeData,
     header: {
       'content-type': 'json'
     }
   });
 });
Example #21
0
export const setGetErrorResponse = (
  path,
  options = {},
  response = RANDOM_ERROR_RESPONSE
) =>
  fetchMock.get(path, response, {
    overwriteRoutes: true,
    ...options
  });
Example #22
0
export const setGetSuccessResponse = (
  path,
  options = {},
  response = RANDOM_SUCCESS_RESPONSE
) =>
  fetchMock.get(path, response, {
    overwriteRoutes: true,
    ...options
  });
 it('should do GET request to /models/1 with id of 1', function () {
   fetchMock.get('/model/1', { id: 1, name: 'hi' });
   const state = showAction(this.dataManager, {
     path: '/model',
     id: 1,
   });
   expect(state.isFetching).toEqual(true);
   expect(fetchMock.called('/model/1')).toEqual(true);
 });
 it("returns parsedReplicationDocs and ignores all design docs", () => {
   fetchMock.getOnce('./_scheduler/jobs', 404);
   fetchMock.get('./_replicator/_all_docs?include_docs=true&limit=100', _repDocs);
   return supportNewApi(true)
     .then(fetchReplicationDocs)
     .then(docs => {
       assert.deepEqual(docs.length, 1);
       assert.deepEqual(docs[0]._id, "c94d4839d1897105cb75e1251e0003ea");
     });
 });
Example #25
0
 test('fails when fetching an invalid round', () => {
   fetchMock.restore();
   fetchMock.post('http://api.afl.com.au/cfs/afl/WMCTok', { token: testValues.token });
   fetchMock.get('*', matchItemsError);
   return getRound('CD_R2017014013').catch((error) => {
     const { code, techMessage } = error;
     expect(code).toBe('CFSAPI001');
     expect(techMessage).toBe('Invalid round id CD_R2017014013');
   });
 });
test('fetch data form server', async (t) => {
  fetchMock.get(API_REGEXP, DUMMY_STREAMING_DATA);
  const streamingData = await fetchStreamingData();
  t.is(streamingData.length, 1);
  const data = streamingData[0];
  t.is(data.link, '%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A');
  t.is(data.title, 'amagami');
  t.is(data.tags.length, 2);
  fetchMock.restore();
});
    it('should contain a valid user ID', async () => {
      document.documentElement.dataset.classifyUrl = '/api/v1/classify/';
      fetchMock.get(urlPathMatcher('/api/v1/classify/'), {
        request_time: '2016-01-01',
        country: 'US',
      });

      const driver = mockNormandy();
      const context = await filterContext(driver);
      expect(context.normandy.userId).toBeDefined();
      expect(UUID_ISH_REGEX.test(context.normandy.userId)).toBe(true);
    });
Example #28
0
		it('should return the transformers', function (done) {
			fetchMock.get('/api/components/names', {
				'@items': {},
			});
			tcomp.Transformers().then(function (resp) {
				expect(resp).toEqual({});
				done();
			}).catch(function (err) {
				expect(err).toBe(null);
				done();
			});
		});
 it('should handle an ERROR', (done) => {
     fetchMock.get('*', 404, {overwriteRoutes: true});
     const testState = {
         foo: 'foo'
     };
     sampleAction()(store.dispatch, store.getState).then((sampleActionResult) => {
         const result = reducer(testState, sampleActionResult);
         expect(result).to.deep.equal(testState);
         expect(store.dispatch).to.be.calledOnce;
         done();
     }).catch(err => done(err));
 });
Example #30
0
  describe('fetchQueryResults', () => {
    const fetchQueryEndpoint = 'glob:*/superset/results/*';
    fetchMock.get(fetchQueryEndpoint, '{ "data": ' + mockBigNumber + ' }');

    const makeRequest = () => {
      const actionThunk = actions.fetchQueryResults(query);
      return actionThunk(dispatch);
    };

    it('makes the fetch request', () => {
      expect.assertions(1);

      return makeRequest().then(() => {
        expect(fetchMock.calls(fetchQueryEndpoint)).toHaveLength(1);
      });
    });

    it('calls requestQueryResults', () => {
      expect.assertions(1);

      return makeRequest().then(() => {
        expect(dispatch.args[0][0].type).toBe(actions.REQUEST_QUERY_RESULTS);
      });
    });

    it('parses large number result without losing precision', () =>
      makeRequest().then(() => {
        expect(fetchMock.calls(fetchQueryEndpoint)).toHaveLength(1);
        expect(dispatch.callCount).toBe(2);
        expect(dispatch.getCall(1).lastArg.results.data.toString()).toBe(mockBigNumber);
      }));

    it('calls querySuccess on fetch success', () =>
      makeRequest().then(() => {
        expect(dispatch.callCount).toBe(2);
        expect(dispatch.getCall(1).args[0].type).toBe(actions.QUERY_SUCCESS);
      }));

    it('calls queryFailed on fetch error', () => {
      expect.assertions(2);
      fetchMock.get(
        fetchQueryEndpoint,
        { throws: { error: 'error text' } },
        { overwriteRoutes: true },
      );

      return makeRequest().then(() => {
        expect(dispatch.callCount).toBe(2);
        expect(dispatch.getCall(1).args[0].type).toBe(actions.QUERY_FAILED);
      });
    });
  });