How to use fetch-mock - 10 common examples

To help you get started, we’ve selected a few fetch-mock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Palindrom / Palindrom / test / specs / client / reconnect.js View on Github external
xit(`should  send HTTP ping`, async () => {         
                    
                    await sleep(pingIntervalS*2*1000 + 10);
                    // ping
                    expect(fetchMock.calls('ping')).to.be.lengthOf.at.least(1, "expected `ping` to be fetched");
                }).timeout(pingIntervalS*3*1000);
            } else {
github Palindrom / Palindrom / test / specs / client / reconnect.js View on Github external
it('should send `HTTP PATCH _remoteUrl_/reconnect` with pending changes in body', async () => {
                    
                    await sleep(pingIntervalS*1000 + 10);
                    // establish
                    expect(fetchMock.calls('establish')).to.be.lengthOf(1, "expected `establish` to be fetched once");
                    expect(fetchMock.called(/testURL/)).to.be.ok;
                    
                    // reconnect
                    expect(fetchMock.calls('reconnect')).to.be.lengthOf(1, "expected `reconnect` to be fetched once");
                    const [reconnectURL, reconnectCall] = fetchMock.lastCall();
                    expect(reconnectURL).to.equal(getTestURL('testURL')+'/reconnect');
                    expect(reconnectCall).to.have.property('body','[[{"op":"replace","path":"/_ver#c$","value":1},{"op":"test","path":"/_ver#s"},{"op":"replace","path":"/hello","value":"OT"}]]');
                    expect(reconnectCall).to.have.property('method','PATCH');
                    expect(reconnectCall.headers).to.have.property('Content-Type','application/json-patch+json');
                    expect(reconnectCall.headers).to.have.property('Accept','application/json');
                }).timeout(pingIntervalS*2*1000);
                describe('when server responds to `/reconnect`', () => {
github Palindrom / Palindrom / test / specs / client / heartbeat.js View on Github external
it(`should send empty patch (\`[]\`) after ${pingIntervalS} seconds after sending local change`, async () => {

                // establish
                expect(fetchMock.calls('establish')).to.be.lengthOf(1);
                expect(fetchMock.called(/testURL/)).to.be.ok;
                
                await sleep(10);
                // change
                palindrom.obj.hello = "Ping Machine";
                await sleep(10);
                expect(fetchMock.calls('patch')).to.be.lengthOf(1, 'should send patch request just after a change');

                await sleep(pingIntervalS*1000 + 10);
                // // ping
                expect(fetchMock.calls('ping')).to.be.lengthOf(1, 'should send ping request `pingIntervalS` after a change');
                const [pingURL, pingCall] = fetchMock.lastCall();
                expect(pingURL).to.equal(getTestURL('testURL'));
                expect(pingCall).to.have.property('body','[]');
                expect(pingCall).to.have.property('method','PATCH');
                expect(pingCall.headers).to.have.property('Content-Type','application/json-patch+json');
                expect(pingCall.headers).to.have.property('Accept','application/json-patch+json');
                
            }).timeout(pingIntervalS*2*1000);
            describe('and server does not respond to send ping within `pingIntervalS`', () => {
github guardian / facia-tool / client-v2 / src / shared / actions / __tests__ / snapcards.spec.ts View on Github external
it("should fetch tag articles and create a corresponding card representing a snap of type 'latest' given user input", async () => {
      fetchMock.once('begin:/api/preview', {
        response: {
          results: [capiArticle, capiArticle],
          tag: { webTitle: 'Example title' }
        }
      });
      fetchMock.once(
        '/http/proxy/https://www.theguardian.com/example/tag/page?view=mobile',
        guardianTagPage
      );
      const store = configureStore(initialState);
      const promise = store.dispatch(createArticleEntitiesFromDrop(
        idDrop('https://www.theguardian.com/example/tag/page')
      ) as any);
      // We can't wait for the entire promise to be done here -- we need to call the modal
      // callbacks in order for the thunk to proceed. However, the modal callbacks are only
      // available on the next event loop tick, so a setTimeout is necessary to ensure they
      // are present.
      setTimeout(() => {
        const options = selectOptionsModalOptions(store.getState());
        // This is effectively simulating clicking a modal option.
        options
          .filter(option => option.buttonText === 'Latest from')
github guardian / facia-tool / client-v2 / src / actions / __tests__ / Fronts.spec.ts View on Github external
it('should fetch all of the front collections, mark  first collections as open, and fetch articles and their analytics data for  first collections', async () => {
      fetchMock.postOnce('/collections', scJohnsonPartnerZoneCollection);
      fetchMock.post('begin:/stories-visible', {
        desktop: 2,
        mobile: 4
      });
      fetchMock.once(
        'begin:/api/preview/search?ids=internal-code/page/5607373,internal-code/page/5607569',
        articlesForScJohnsonPartnerZone
      );

      // @todo -- this isn't checking the correct thing -- we'd expect article paths in this string.
      // See below -- the articles don't end up in the state as expected.
      fetchMock.get(
        '/ophan/histogram?referring-path=/sc-johnson-partner-zone&hours=1&interval=10',
        []
      );
github voluntarily / vly2 / components / Interest / __tests__ / InterestSection.spec.js View on Github external
test('mount the InterestSection with two interests', async t => {
  const realStore = makeStore(initStore)
  const myMock = fetchMock.sandbox()
  reduxApi.use('fetch', adapterFetch(myMock))
  myMock.getOnce(`${API_URL}/interests/?op=${opid}`, interests)
  myMock.putOnce(`${API_URL}/interests/${interestid}`, invitedAndrew)

  const wrapper = await mountWithIntl(
    
      
    
  )
  await sleep(1) // allow asynch fetch to complete
  wrapper.update()
  t.is(wrapper.find('tbody tr').length, 2)
  t.regex(wrapper.find('tbody tr td').at(1).text(), /avowkind/)
  t.regex(wrapper.find('tbody tr').at(1).find('td').at(1).text(), /Dali/)

  // test invite button
github Rsullivan00 / apollo-link-json-api / src / __tests__ / jsonApiLink.ts View on Github external
it.skip('with correctly encoded params', async () => {
    // expect.assertions(4);

    const link = new JsonApiLink({ uri: '/api' });
    const posts1 = [{ id: '1', title: 'Love apollo' }];
    // This is an invalid URL because it doesn't have an encoded space, this is to prove
    // we didn't encode it if it wasn't prefixed by '?' or '&' ?{args} or &{args}
    fetchMock.get('/api/posts?name=Love apollo', posts1);
    // This URL is legacy (shouldn't be called)
    fetchMock.get('/api/posts?name=Love+apollo', posts1);
    // This URL is correctly encoded
    fetchMock.get('/api/posts?name=Love%20apollo', posts1);
    // Uses a query string & a path replacement
    fetchMock.get('/api/posts/1?comments=5', posts1);

    const nonEncodedQuery = gql`
      query postQuery($name: String) {
        posts(name: $name)
          @jsonapi(type: "Post", path: "/posts?name={args.name}") {
          id
          title
        }
      }
    `;
    const encodedQuery = gql`
      query postQuery($name: String) {
        posts(name: $name) @jsonapi(type: "Post", path: "/posts?{args}") {
          id
github blockstack / blockstack.js / tests / unitTests / src / unitTestsStorage.js View on Github external
'name': 'Ken Liao',
              'apps': {
                'http://localhost:8080': 'https://gaia.blockstack.org/hub/1DDUqfKtQgYNt722wuB4Z2fPC7aiNGQa5R/'
              }
            }
          },
          'signature': 'UyQNZ02kBFHEovbwiGaS-VQd57w9kcwn1Nt3QbW3afEMArg1OndmeplB7lzjMuRCLAi-88lkpQLkFw7LwKZ31Q'
        }
      }
    ]
    /* eslint-enable */
    FetchMock.get(profileUrl, profileContent)

    const fileUrl = 'https://gaia.blockstack.org/hub/1DDUqfKtQgYNt722wuB4Z2fPC7aiNGQa5R/file.json'
    const fileContents = JSON.stringify({ key: 'value' })
    FetchMock.get(fileUrl, fileContents)

    const options = {
      username: 'yukan.id',
      app: 'http://localhost:8080'
    }

    getFile(path, options)
      .then((file) => {
        t.ok(file, 'Returns file content')
        t.same(JSON.parse(file), JSON.parse(fileContents))
      })

    const optionsNoApp = {
      username: 'yukan.id'
    }
github Rsullivan00 / apollo-link-json-api / src / __tests__ / jsonApiLink.ts View on Github external
query: encodedQuery,
        variables: { name: 'Love apollo' },
      }),
    );

    expect(fetchMock.called('/api/posts?name=Love%20apollo')).toBe(true);

    await makePromise(
      execute(link, {
        operationName: 'postQuery',
        query: mixedQuery,
        variables: { id: 1, query: { comments: 5 } },
      }),
    );

    expect(fetchMock.called('/api/posts/1?comments=5')).toBe(true);
  });
  // TODO: Test for Path using context
github teambition / teambition-sdk / test / apis / scenariofieldconfig.spec.ts View on Github external
const customfieldlinksUrl = `/projects/${projectId}/customfieldlinks?boundType=application&withRootCommongroup=true&_=666`
    fetchMock.getOnce(customfieldlinksUrl, [customFieldLink])

    // 缓存 CustomFieldLink 数据
    yield sdk
      .getCustomFieldLinks(projectId, 'application')
      .values()
      .subscribeOn(Scheduler.asap)
      .do(() => {
        expect(fetchMock.called(customfieldlinksUrl)).to.be.true
      })

    // 请求 CustomField 数据,无权限
    const customFieldUrl = `/customfields/${customFieldId}?_=666`
    fetchMock.getOnce(customFieldUrl, 403)

    yield configs$.do(([result]) => {
      assertScenarioFieldConfig(result, {
        ...config,
        ...nextConfig,
        scenariofields: [{ ...nextScenarioField, customfield: customField }]
      })

      expect(fetchMock.called(customFieldUrl)).to.be.true
    })
  })