How to use the fetch-mock.once function in fetch-mock

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 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 manifoldco / ui / src / utils / restFetch.spec.ts View on Github external
it('Will retry if the token is refreshed', async () => {
        const fetcher = createRestFetch({
          wait: () => 1,
          getAuthToken: () => '12344',
          retries: 1,
        });

        const body = { title: 'test' };

        fetchMock
          .once('path:/v1/test', 401)
          .mock('path:/v1/test', { status: 200, body }, { overwriteRoutes: false });

        const fetch = fetcher({
          endpoint: '/test',
          service: 'marketplace',
        });

        /* Queue the dispatch back a tick to allow listeners to be set up */
        await new Promise(resolve => {
          setTimeout(() => {
            document.dispatchEvent(
              new CustomEvent('manifold-token-receive', { detail: { token: '12344' } })
            );

            resolve();
github panjiesw / frest / test / frest / Frest.ts View on Github external
it('Must call correct endpoint with array path', (done) => {
			fetchMock.once('test/test2', { status: 200 }, { name: 'test', method: 'GET' });
			const frest = new Frest();
			frest.request({ path: ['test', 'test2'], method: 'GET' }).then((res) => {
				if (res) {
					expect(fetchMock.called('test')).toBe(true);
					expect(res.origin.status).toBe(200);
					done();
				} else {
					done.fail('No response returned');
				}
			}).catch(done.fail);
		});
github teambition / teambition-sdk / test / apis / scenariofieldconfig.spec.ts View on Github external
it('should create a new ScenarioFieldConfig', function*() {
    const configId = 'mock-sfc-id' as ScenarioFieldConfigId
    const orgId = 'mock-org-id' as OrganizationId
    const objectType = 'task'
    const config = {
      _id: configId,
      _boundToObjectId: orgId,
      objectType,
      scenariofields: []
    }

    fetchMock.once('*', { result: [] })

    const configs$ = sdk
      .getOrgScenarioFieldConfigs(orgId, objectType)
      .take(1)
      .subscribeOn(Scheduler.asap)

    yield configs$.do((result) => {
      expect(result).to.deep.equal([])
    })

    fetchMock.once('*', config)

    yield sdk
      .createOrgScenarioFieldConfig(orgId, {
        _boundToObjectId: orgId,
        objectType
github guardian / facia-tool / client-v2 / src / actions / __tests__ / Collections.spec.ts View on Github external
it('should dispatch start and error actions when something goes wrong', async () => {
      fetchMock.once('begin:/api/preview/internal-code/page/1', 400);
      await store.dispatch(fetchArticles(['internal-code/page/1']) as any);
      const actions = store.getActions();
      expect(actions[0]).toEqual(
        externalArticleActions.fetchStart(['internal-code/page/1'])
      );
      expect(actions[1].type).toEqual(externalArticleActionNames.fetchError);
    });
    it("should not add articles to the state if they're not stale", async () => {
github panjiesw / frest / packages / frest / src / __tests__ / frest / interceptors.ts View on Github external
test('error interceptor recovered', async t => {
  const url = `${BASE}/error-recovered`;
  const fm = fetchMock.once(url, {
    body: {
      error: 'test',
    },
    status: 401,
  });
  const int = sinon.stub().callsFake(async (err: IFrestError) => {
    if (err.response) {
      const value = await err.response.origin.json();
      err.response.body = value;
      return err.response;
    }
    return null;
  });

  const frest = new Frest({
    base: BASE,
github wp-headless / fetch / packages / client / __tests__ / Transport / index.spec.js View on Github external
['POST', 'PUT', 'PATCH'].forEach(method => {
    fetchMock.once('*', {}, { method });
    transport.request('https://wp.com/wp-json', { method, json: undefined });
    expect(fetchMock.calls()[0][1].headers).toEqual(undefined);
  });
});
github coalescejs / coalesce / tests / acceptance / simple-hierarchy.spec.js View on Github external
);

    let { session } = this;
    let parentSession = session;

    let post = await session.find(Post, 1);
    let comment1 = await post.comments.get(0).load();
    let comment2 = await post.comments.get(1).load();

    session = parentSession.child();
    post = session.fetch(post);

    post.comments.push(session.create(Comment, { body: 'Third' }));
    post.title = 'Rough Draft 2';

    fetchMock.once(
      '/posts/1',
      JSON.stringify({
        type: 'post',
        id: 1,
        rev: 2,
        title: 'Rough Draft',
        content: 'This is some different content',
        user: 2,
        comments: [3, 4, 5]
      })
    );

    await post.refresh();
    session.merge(parentSession.get(post.comments));

    expect(post.title).to.eq('Rough Draft 2');
github jamaljsr / polar / src / lib / lightning / clightning / clightningApi.spec.ts View on Github external
it('should perform a successful httpPost', async () => {
    fetchMock.once('end:/post-ok', { success: true });
    const res = await httpPost(node, 'post-ok', { data: 'asdf' });
    expect(res).toEqual({ success: true });
    const lastCall = fetchMock.lastCall() as any;
    expect(lastCall).toBeInstanceOf(Array);
    expect(lastCall[1].body).toEqual('{"data":"asdf"}');
  });
github jamaljsr / polar / src / lib / lightning / clightning / clightningApi.spec.ts View on Github external
it('should perform a successful httpGet', async () => {
    fetchMock.once('end:/get-ok', { success: true });
    const res = await httpGet(node, 'get-ok');
    expect(res).toEqual({ success: true });
  });