@testing-library/react-hooks#renderHook JavaScript Examples

The following examples show how to use @testing-library/react-hooks#renderHook. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useReduxContext.spec.js    From Learning-Redux with MIT License 7 votes vote down vote up
describe('React', () => {
  describe('hooks', () => {
    describe('useReduxContext', () => {
      it('throws if component is not wrapped in provider', () => {
        const spy = jest.spyOn(console, 'error').mockImplementation(() => {})

        const { result } = renderHook(() => useReduxContext())

        expect(result.error.message).toMatch(
          /could not find react-redux context value/
        )

        spy.mockRestore()
      })
    })
  })
})
Example #2
Source File: test-utils.js    From flame-coach-web with MIT License 6 votes vote down vote up
customHookRender = (ui, options) => {
  return renderHook(ui, { wrapper: AllTheProviders, ...options });
}
Example #3
Source File: useActivationKey.test.js    From sed-frontend with Apache License 2.0 6 votes vote down vote up
describe('useActivationKey', () => {
  beforeEach(() => {
    Object.defineProperty(window, 'insights', {
      value: {
        chrome: {
          auth: {
            getToken: jest.fn(),
          },
        },
      },
    });
  });
  it('returns activation key details from the API', async () => {
    const keyData = [
      {
        name: 'A',
        role: 'role',
        sla: 'sla',
        usage: 'usage',
      },
    ];

    fetch.mockResponseOnce(JSON.stringify({ body: [...keyData] }));

    const { result, waitFor } = renderHook(() => useActivationKey('A'), {
      wrapper: createQueryWrapper(),
    });

    await waitFor(() => result.current.isSuccess);

    expect(result.current.data).toEqual(keyData);
  });
});
Example #4
Source File: useFilterConfig.test.js    From tasks-frontend with Apache License 2.0 6 votes vote down vote up
describe('useFilterConfig', () => {
  it('returns a filter config configuration', () => {
    const { result } = renderHook(() =>
      useFilterConfig({ filters: { filterConfig: filters } })
    );
    expect(result.current).toMatchSnapshot();
  });

  it('works concurrently', () => {
    const component = (
      <>
        <FilterItemsMockComponent filters={filters.slice(2)} />
        <FilterItemsMockComponent filters={filters} />
      </>
    );
    const { container } = render(component);

    expect(container).toMatchSnapshot();
  });
});
Example #5
Source File: useArrayRef.spec.js    From custom-hooks with MIT License 6 votes vote down vote up
describe('useArrayRef hook', () => {
  it('should return an array with ref stored at every index', () => {
    const { rerender, result } = renderHook(({ size }) => useArrayRef(size), {
      initialProps: { size: 3 },
    });
    expect(result.current.length).toBe(3);
    expect(result.current).toEqual(expect.arrayContaining([{ current: null }]));
    rerender({ size: 4 });
    expect(result.current.length).toBe(4);
  });
  it('should return the previous instance after rerender if size is same', () => {
    const { rerender, result } = renderHook(({ size }) => useArrayRef(size), {
      initialProps: { size: 3 },
    });
    const result1 = result.current;
    rerender({ size: 3 });
    expect(result.current).toStrictEqual(result1);
  });
  it('should remove copy the previous refs when size changes after rerender', () => {
    const { rerender, result } = renderHook(({ size }) => useArrayRef(size), {
      initialProps: { size: 3 },
    });
    result.current[0].current = 1;
    rerender({ size: 4 });
    expect(result.current[0].current).toBe(1);
  });
});
Example #6
Source File: useBreedList.test.js    From citr-v6-project with Apache License 2.0 6 votes vote down vote up
// function getBreedList(animal) {
//   let list;

//   function TestComponent() {
//     list = useBreedList(animal);
//     return null;
//   }

//   render(<TestComponent />);

//   return list;
// }

test("gives an empty list with no animal", async () => {
  // const [breedList, status] = getBreedList();

  const { result } = renderHook(() => useBreedList(""));

  const [breedList, status] = result.current;

  expect(breedList).toHaveLength(0);
  expect(status).toBe("unloaded");
});
Example #7
Source File: useDateInput.test.js    From react-nice-dates with MIT License 6 votes vote down vote up
describe('useDateInput', () => {
  test('should return input props', () => {
    const { result } = renderHook(() => useDateInput({
      locale: enGB,
      onDateChange: () => {}
    }))

    expect(result.current).toMatchObject({
      onFocus: expect.any(Function),
      onChange: expect.any(Function),
      onBlur: expect.any(Function),
      placeholder: enGB.formatLong.date({ width: 'short' }).toLowerCase(),
      type: 'text',
      value: ''
    })
  })
})
Example #8
Source File: rtl.testutil.js    From kafka-java-vertx-starter with Apache License 2.0 6 votes vote down vote up
customRenderHook = (callback) => {
  const { result, ...others } = renderHook(callback);
  return {
    getResultFromHook: (key) => (key ? result.current[key] : result.current),
    result,
    ...others,
  };
}
Example #9
Source File: index.test.jsx    From erp-crm with MIT License 6 votes vote down vote up
test('Test useNetwork', () => {
  const { result } = renderHook(() => useNetwork());
  window.ononline = () => {
    expect(result.current.isOnline).toBe(true);
  };
  window.onoffline = () => {
    expect(result.current.isOnline).toBe(false);
  };
});
Example #10
Source File: use-currency.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('use-currency tests', () => {
  let renderedHook;

  beforeAll(async () => {
    renderedHook = renderHook(() => useCurrency(), { wrapper });

    await new Promise((resolve) => setTimeout(resolve, 0));
  });

  it('should return currency sign', () => {
    expect(renderedHook.result.current.getCurrencySign()).toStrictEqual(<HryvniaIcon />);
  });

  it('should return value with currency', () => {
    expect(renderedHook.result.current.getPriceWithCurrency(10)).toEqual(300);
  });

  it('should return base price', () => {
    expect(renderedHook.result.current.getBaseCurrencyPrice(900)).toEqual(30);
  });
});
Example #11
Source File: index.test.js    From react-fluid-table with MIT License 6 votes vote down vote up
describe('useMyHook', () => {
  it('updates every second', () => {
    const { result } = renderHook(() => useMyHook());

    expect(result.current).toBe(0);

    // Fast-forward 1sec
    act(() => {
      jest.advanceTimersByTime(1000);
    });

    // Check after total 1 sec
    expect(result.current).toBe(1);

    // Fast-forward 1 more sec
    act(() => {
      jest.advanceTimersByTime(1000);
    });

    // Check after total 2 sec
    expect(result.current).toBe(2);
  })
})
Example #12
Source File: useActiveDescendantListFocus.jest.js    From monday-ui-react-core with MIT License 6 votes vote down vote up
function renderHookForTest({ onItemClick = jest.fn(), isItemSelectable = () => true, isHorizontal = false }) {
  element = document.createElement("div");
  element.tabIndex = -1; // some tests focus the element - a tabIndex value is required for updating the document.activeIndex value
  document.body.appendChild(element);

  return renderHook(() =>
    useActiveDescendantListFocus({
      focusedElementRef: {
        current: element
      },
      itemsIds: ITEM_IDS,
      isItemSelectable: isItemSelectable,
      onItemClick,
      isHorizontalList: isHorizontal
    })
  );
}
Example #13
Source File: useNormalizedValue.spec.js    From rainbow-modules with MIT License 6 votes vote down vote up
describe('useNormalizedValue', () => {
    it('should return same value', () => {
        const date = new Date(2019, 0, 1);
        const { result } = renderHook(() => useNormalizedValue(date));
        expect(result.current).toEqual(date);
    });
    it('should return new changed value if value is not the same day', () => {
        const date1 = new Date(2019, 0, 1);
        const date2 = new Date(2019, 0, 1);
        const hook = renderHook((value) => useNormalizedValue(value), {
            initialProps: date1,
        });
        expect(hook.result.current).toEqual(date1);
        hook.rerender(date2);
        expect(hook.result.current).toEqual(date2);
    });
    it('should return memoized value if value is the same day', () => {
        const date1 = new Date(2019, 0, 1);
        const date2 = new Date(2019, 0, 1, 23, 59, 59, 999);
        const hook = renderHook((value) => useNormalizedValue(value), {
            initialProps: date1,
        });
        expect(hook.result.current).toEqual(date1);
        hook.rerender(date2);
        expect(hook.result.current).toEqual(date1);
    });
});
Example #14
Source File: useAccountQuery.test.js    From v3-ui with MIT License 6 votes vote down vote up
describe('useAccountQuery', () => {
  // Currently using AuthControllerContext in hook requires a lot more boilerplate
  xit('santizes the address', async () => {
    const queryCache = new QueryCache()

    // const contextValues = { chainId: 1 }

    const wrapper = ({ children }) => (
      <ReactQueryCacheProvider queryCache={queryCache}>{children}</ReactQueryCacheProvider>
    )

    const expectation = nock('https://api.thegraph.com')
      .get('/subgraphs/name/pooltogether/pooltogether-v3_1_0')
      .reply(200, {
        answer: 42
      })

    const { result, waitFor } = renderHook(() => useAccountQuery(), { wrapper })

    await waitFor(() => {
      return result.current.isSuccess
    })

    expect(result.current).toEqual({ answer: 42 })
  })
})
Example #15
Source File: useEffectOnce.test.js    From tonic-ui with MIT License 6 votes vote down vote up
describe('useEffectOnce', () => {
  beforeEach(() => {
    // Clear mock function called times
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(useEffectOnce).toBeDefined();
  });

  it('should run provided effect only once', () => {
    const { rerender } = renderHook(() => useEffectOnce(mockEffectCallback));
    expect(mockEffectCallback).toHaveBeenCalledTimes(1);
    rerender();
    expect(mockEffectCallback).toHaveBeenCalledTimes(1);
  });

  it('should run the clean-up function when unmounting', () => {
    const { unmount } = renderHook(() => useEffectOnce(mockEffectCallback));
    expect(mockEffectCleanup).not.toHaveBeenCalled();
    unmount();
    expect(mockEffectCleanup).toHaveBeenCalledTimes(1);
  });
});
Example #16
Source File: useAuth.js    From plataforma-sabia with MIT License 6 votes vote down vote up
describe('userAuth', () => {
	it('can setUser and logout', () => {
		const { result } = renderHook(() => useAuth(), { wrapper });

		expect(result.current.user).toEqual({});

		act(() => {
			result.current.setUser(testUser);
		});

		expect(result.current.user).toEqual(testUser);

		act(() => {
			result.current.logout();
		});

		expect(result.current.user).toEqual({});
	});
});
Example #17
Source File: useAllResponsiveProps.test.js    From basis with MIT License 5 votes vote down vote up
describe("useAllResponsiveProps", () => {
  it("collects all the responsive props", () => {
    const props = {
      padding: "4",
      "padding-xs": 5,
      "padding-sm": "0",
      "padding-md": "6",
      "padding-lg": "1 2 3",
      "padding-xl": "0 8",
      anotherProp: "some value",
    };
    const { result } = renderHook(
      () => useAllResponsiveProps(props, "padding"),
      { wrapper: TestWrapper }
    );

    expect(result.current).toStrictEqual({
      padding: "4",
      "padding-xs": 5,
      "padding-sm": "0",
      "padding-md": "6",
      "padding-lg": "1 2 3",
      "padding-xl": "0 8",
    });
  });

  it("drops responsive props that do not exist", () => {
    const props = {
      "padding-xs": 5,
      "padding-md": "6",
      anotherProp: "some value",
    };
    const { result } = renderHook(
      () => useAllResponsiveProps(props, "padding"),
      { wrapper: TestWrapper }
    );

    expect(result.current).toStrictEqual({
      "padding-xs": 5,
      "padding-md": "6",
    });
  });
});
Example #18
Source File: useAppReview-test.js    From react-native-in-app-review with MIT License 5 votes vote down vote up
describe('App Review Hook Behavoir', () => {
  const currentDate = new Date('2021-01-10T11:01:58.135Z');
  global.Date = class extends Date {
    constructor(date) {
      if (date) {
        return super(date);
      }

      return currentDate;
    }
  };
  afterAll(() => {
    jest.resetModule();
  });

  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should trigger InAppReview in cross platform in first time', async () => {
    const expectItemSavedToAsync = ['in_App_Review', new Date().toString()];

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());
    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');
    expect(AsyncStorage.setItem).toHaveBeenCalledWith(
      ...expectItemSavedToAsync,
    );

    expect(InAppReview.RequestInAppReview).toHaveBeenCalled();
  });

  it('should not trigger InAppReview before 15 days user already get InAppReview', async () => {
    const expectedItem = '2021-01-05';
    jest
      .spyOn(AsyncStorage, 'getItem')
      .mockReturnValueOnce(Promise.resolve(expectedItem));

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());
    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');

    expect(InAppReview.RequestInAppReview).not.toHaveBeenCalled();
  });

  it('should trigger InAppReview after 15 days user get InAppReview and save Date to async Storage', async () => {
    const expectedItem = '2021-01-26';
    const expectItemSavedToAsync = ['in_App_Review', new Date().toString()];

    jest
      .spyOn(AsyncStorage, 'getItem')
      .mockReturnValueOnce(Promise.resolve(expectedItem));

    jest.spyOn(AsyncStorage, 'setItem');

    const {result} = renderHook(() => useAppReview());

    await act(() => result.current.onReview());

    expect(AsyncStorage.getItem).toBeCalledWith('in_App_Review');
    expect(AsyncStorage.setItem).toHaveBeenCalledWith(
      ...expectItemSavedToAsync,
    );
    expect(InAppReview.RequestInAppReview).toHaveBeenCalled();
  });
});
Example #19
Source File: useExport.test.js    From tasks-frontend with Apache License 2.0 5 votes vote down vote up
describe('useExport', () => {
  let workingExporter = jest.fn(() => Promise.resolve(items));
  let defaultOptions;

  beforeEach(() => {
    defaultOptions = {
      columns,
    };
  });

  it('returns an export config toolbar config', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() => useExport(defaultOptions));
    expect(result.current.toolbarProps.exportConfig).toBeDefined();
    expect(result).toMatchSnapshot();
  });

  it('returns an export config toolbar config', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() =>
      useExport({
        ...defaultOptions,
        isDisabled: true,
      })
    );
    expect(result.current.toolbarProps.exportConfig.isDisabled).toBe(true);
  });

  it('calls the exporter via onSelect', () => {
    defaultOptions.exporter = workingExporter;
    const { result } = renderHook(() => useExport(defaultOptions));

    act(() => {
      result.current.toolbarProps.exportConfig.onSelect(null, 'csv');
    });

    expect(defaultOptions.exporter).toHaveBeenCalled();

    act(() => {
      result.current.toolbarProps.exportConfig.onSelect(null, 'json');
    });

    expect(defaultOptions.exporter).toHaveBeenCalled();
  });
});
Example #20
Source File: useWorker.test.js    From useWorker with MIT License 5 votes vote down vote up
it("Runs successfully", async () => {
  const sum = (a, b) => a + b;
  const { result } = renderHook(() => useWorker(sum));
  const [sumWorker] = result.current;
  const res = await sumWorker(1, 2);
  assert.equal(res, 3);
});
Example #21
Source File: bubble-map.test.js    From ant-design-charts with MIT License 5 votes vote down vote up
refs = renderHook(() => useRef())
Example #22
Source File: useOnClickOutside.spec.js    From custom-hooks with MIT License 5 votes vote down vote up
describe('useOnClickOutside hook', () => {
  it('should call the callback passed when click outside the passed ref', () => {
    const callbackFunc = jest.fn();
    const ref = { current: document.getElementById('sibling-a') };
    renderHook(({ callback }) => useOnClickOutside(ref, callback), {
      initialProps: { callback: callbackFunc },
    });
    triggerClick('sibling-b');
    expect(callbackFunc).toHaveBeenCalled();
  });
  it('should not call the callback passed when click inside the passed ref', () => {
    const callback = jest.fn();
    const ref = { current: document.getElementById('parent') };
    renderHook(() => useOnClickOutside(ref, callback));
    triggerClick('sibling-b');
    expect(callback).not.toHaveBeenCalled();
  });
  it('should call the updated callback passed in last render', () => {
    const callbackFuncA = jest.fn();
    const ref = { current: document.getElementById('sibling-a') };

    const { rerender } = renderHook(({ elRef, callback }) => useOnClickOutside(elRef, callback), {
      initialProps: { callback: callbackFuncA, elRef: ref },
    });
    const callbackFuncB = jest.fn();
    rerender({ elRef: ref, callback: callbackFuncB });
    triggerClick('sibling-b');
    expect(callbackFuncA).not.toHaveBeenCalled();
    expect(callbackFuncB).toHaveBeenCalled();
  });
  it('should not call the callback passed after unmount', () => {
    const callbackFunc = jest.fn();
    const ref = { current: document.getElementById('sibling-a') };
    const { unmount } = renderHook(({ callback }) => useOnClickOutside(ref, callback), {
      initialProps: { callback: callbackFunc },
    });
    unmount();
    triggerClick('sibling-b');
    expect(callbackFunc).not.toHaveBeenCalled();
  });
  it('should not call the callback passed after rerender and then unmount', () => {
    const callbackFunc = jest.fn();
    const ref = { current: document.getElementById('sibling-a') };
    const { unmount, rerender } = renderHook(({ callback }) => useOnClickOutside(ref, callback), {
      initialProps: { callback: callbackFunc },
    });
    rerender();
    unmount();
    triggerClick('sibling-b');
    expect(callbackFunc).not.toHaveBeenCalled();
  });
});
Example #23
Source File: useDispatch.spec.js    From Learning-Redux with MIT License 5 votes vote down vote up
describe('React', () => {
  describe('hooks', () => {
    describe('useDispatch', () => {
      it("returns the store's dispatch function", () => {
        const { result } = renderHook(() => useDispatch(), {
          wrapper: (props) => <ProviderMock {...props} store={store} />,
        })

        expect(result.current).toBe(store.dispatch)
      })
    })
    describe('createDispatchHook', () => {
      it("returns the correct store's dispatch function", () => {
        const nestedContext = React.createContext(null)
        const useCustomDispatch = createDispatchHook(nestedContext)
        const { result } = renderHook(() => useDispatch(), {
          // eslint-disable-next-line react/prop-types
          wrapper: ({ children, ...props }) => (
            <ProviderMock {...props} store={store}>
              <ProviderMock context={nestedContext} store={store2}>
                {children}
              </ProviderMock>
            </ProviderMock>
          ),
        })

        expect(result.current).toBe(store.dispatch)

        const { result: result2 } = renderHook(() => useCustomDispatch(), {
          // eslint-disable-next-line react/prop-types
          wrapper: ({ children, ...props }) => (
            <ProviderMock {...props} store={store}>
              <ProviderMock context={nestedContext} store={store2}>
                {children}
              </ProviderMock>
            </ProviderMock>
          ),
        })

        expect(result2.current).toBe(store2.dispatch)
      })
    })
  })
})
Example #24
Source File: index.test.js    From use-infinite-scroll with MIT License 5 votes vote down vote up
describe('useInfiniteScroll', () => {
  let hook;
  let scrollerNode = document.createElement('div');
  let loaderNode = document.createElement('div');

  beforeEach(async () => {
    hook = renderHook(({ hasMore }) => useInfiniteScroll({ hasMore }), {
      initialProps: { hasMore: false },
    });
    const [, loaderRef, scrollerRef] = hook.result.current;
    loaderRef.current = loaderNode;
    scrollerRef.current = scrollerNode;

    hook.rerender({ hasMore: true });
  });

  it('first page should be 0', () => {
    const [page] = hook.result.current;
    expect(page).toBe(0);
  });

  it('should observe the loader node', () => {
    const observer = intersectionMockInstance(loaderNode);
    expect(observer).toBeDefined();
    expect(observer.observe).toHaveBeenCalledWith(loaderNode);
  });

  it('should switch to next page when reaching loaderNode intersection', () => {
    act(() => mockIsIntersecting(loaderNode, true));
    const [page] = hook.result.current;
    expect(page).toBe(1);
  });

  it('should disconnect when there are no more results', () => {
    const observer = intersectionMockInstance(loaderNode);
    expect(observer.disconnect).not.toHaveBeenCalled();

    hook.rerender({ hasMore: false });
    expect(observer.disconnect).toHaveBeenCalled();
  });
});
Example #25
Source File: index.test.js    From use-shopping-cart with MIT License 5 votes vote down vote up
function reload(overrides) {
  window.localStorage.clear()
  const { result } = renderHook(() => useShoppingCart((state) => state), {
    wrapper: createWrapper(overrides)
  })
  return result
}
Example #26
Source File: useClickOutside.jest.js    From monday-ui-react-core with MIT License 5 votes vote down vote up
describe("useClickOutside", () => {
  let element;
  let callbackStub;

  beforeEach(() => {
    callbackStub = jest.fn();
    element = document.createElement("div");
    document.body.appendChild(element);
    renderHook(() => useOnClickOutside({ ref: { current: element }, callback: callbackStub }));
  });

  afterEach(() => {
    element.remove();
    cleanup();
  });
  describe("mouseDown", () => {
    it("should call the callback when click outside the element", () => {
      act(() => {
        fireEvent.click(document.body);
      });
      return expect(callbackStub.mock.calls.length).toEqual(1);
    });

    it("should not call the callback when clicking the element", () => {
      act(() => {
        fireEvent.click(element);
      });
      return expect(callbackStub.mock.calls.length).toEqual(0);
    });
  });

  describe("touchStart", () => {
    it("should call the callback when click outside the element", () => {
      act(() => {
        fireEvent.touchEnd(document.body);
      });
      return expect(callbackStub.mock.calls.length).toEqual(1);
    });

    it("should not call the callback when clicking the element", () => {
      act(() => {
        fireEvent.touchEnd(element);
      });
      return expect(callbackStub.mock.calls.length).toEqual(0);
    });
  });
});
Example #27
Source File: useCalendarBounds.spec.js    From rainbow-modules with MIT License 5 votes vote down vote up
describe('useCalendarBounds', () => {
    it('should return minDate and maxDate as bounds when date is between them', () => {
        const date = new Date(2019, 0, 1);
        const minDate = new Date(2018, 0, 1);
        const maxDate = new Date(2020, 0, 1);
        const bounds = {
            minCalendarDate: minDate,
            maxCalendarDate: maxDate,
        };
        const { result } = renderHook(() =>
            useCalendarBounds({ minDate, maxDate, currentValue: date }),
        );
        expect(result.current).toEqual(bounds);
    });
    it('should return date and maxDate as bounds when date is below minDate', () => {
        const date = new Date(2018, 0, 1);
        const minDate = new Date(2019, 0, 1);
        const maxDate = new Date(2020, 0, 1);
        const bounds = {
            minCalendarDate: date,
            maxCalendarDate: maxDate,
        };
        const { result } = renderHook(() =>
            useCalendarBounds({ minDate, maxDate, currentValue: date }),
        );
        expect(result.current).toEqual(bounds);
    });
    it('should return minDate and date as bounds when date is beyond maxDate', () => {
        const date = new Date(2021, 0, 1);
        const minDate = new Date(2019, 0, 1);
        const maxDate = new Date(2020, 0, 1);
        const bounds = {
            minCalendarDate: minDate,
            maxCalendarDate: date,
        };
        const { result } = renderHook(() =>
            useCalendarBounds({ minDate, maxDate, currentValue: date }),
        );
        expect(result.current).toEqual(bounds);
    });
});
Example #28
Source File: index.test.js    From react-use-opentok with MIT License 5 votes vote down vote up
describe('session initialization and connection', () => {
  it('initSession', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;

    expect(opentokProps.session).toBeUndefined();
    expect(opentokProps.isSessionInitialized).toBeFalsy();
    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.session).toBeDefined();
    expect(opentokProps.isSessionInitialized).toBeTruthy();
  });

  it('connectSession', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;

    try {
      await act(() => opentokMethods.connectSession(MOCK_CREDENTIALS.token));
    } catch (error) {
      expect(error).toMatch(/session/);
    }

    await act(() => opentokMethods.initSession(MOCK_CREDENTIALS));

    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.isSessionConnected).toBeFalsy();
    expect(opentokProps.connectionId).toBeUndefined();

    try {
      await act(() => opentokMethods.connectSession());
    } catch (error) {
      expect(error).toMatch(/token/);
    }

    [opentokProps, opentokMethods] = result.current;
    await act(() =>
      opentokMethods.connectSession(
        MOCK_CREDENTIALS.token,
        opentokProps.session
      )
    );
    [opentokProps, opentokMethods] = result.current;
    expect(opentokProps.isSessionConnected).toBeTruthy();
    expect(opentokProps.connectionId).toEqual(expect.any(String));
  });

  it('initSessionAndConnect', async () => {
    const { result } = renderHook(() => reactUseOpentok());
    let [opentokProps, opentokMethods] = result.current;
    // expect(1).toBe(1);
    expect(opentokProps.session).toBeUndefined();
    expect(opentokProps.isSessionConnected).toBeFalsy();
    expect(opentokProps.connectionId).toBeUndefined();

    await act(() => opentokMethods.initSessionAndConnect(MOCK_CREDENTIALS));
    // [opentokProps, opentokMethods] = result.current;

    // expect(opentokProps.session).toBeDefined();
    // expect(opentokProps.isSessionConnected).toBeTruthy();
    // expect(opentokProps.connectionId).toEqual(expect.any(String));
  });
});
Example #29
Source File: useGeoLocation.test.js    From js-miniapp with MIT License 5 votes vote down vote up
describe('useGeoLocation', () => {
  let result;
  const dummyCoordinates = {
    latitude: 51.1,
    longitude: 45.3,
  };
  const mockGeolocation = {
    watchPosition: jest.fn(),
    clearWatch: jest.fn(),
    getCurrentPosition: jest.fn().mockImplementation((success) =>
      Promise.resolve(
        success({
          coords: dummyCoordinates,
        })
      )
    ),
  };
  beforeEach(() => {
    result = renderHook(() => useGeoLocation()).result;
    navigator.geolocation = mockGeolocation;
    MiniApp.requestLocationPermission = jest.fn().mockResolvedValue('');
  });

  test('should initialize location hook', () => {
    const [state] = result.current;
    expect(state.isWatching).toEqual(false);
    expect(state.location).toBeUndefined();
  });

  test('should watch location coordinates when permission granted', async () => {
    MiniApp.requestLocationPermission = jest.fn().mockResolvedValue('');

    let [state, watch] = result.current;
    await act(() => watch());
    [state] = result.current;

    expect(state.isWatching).toEqual(true);
    expect(state.location).toEqual(dummyCoordinates);
  });

  test('should not watch location when permission not granted', async () => {
    MiniApp.requestLocationPermission = jest.fn().mockRejectedValue('');

    let [state, watch] = result.current;
    await act(() => watch());
    [state] = result.current;

    expect(state.isWatching).toEqual(false);
    expect(state.location).not.toEqual(dummyCoordinates);
  });

  test('should stop watching location coordinates', async () => {
    let [state, watch, unwatch] = result.current;
    await act(() => watch());
    [state] = result.current;
    expect(state.isWatching).toEqual(true);
    expect(state.location).toEqual(dummyCoordinates);
    act(() => unwatch());
    [state] = result.current;
    expect(state.isWatching).toEqual(false);
    expect(state.location).toBeUndefined();
  });
});