sso-context.test.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { expect } from 'chai'
  2. import { renderHook } from '@testing-library/react-hooks'
  3. import {
  4. SSOProvider,
  5. useSSOContext,
  6. } from '../../../../../frontend/js/features/settings/context/sso-context'
  7. import fetchMock from 'fetch-mock'
  8. const mockOauthProviders = {
  9. google: {
  10. descriptionKey: 'login_with_service',
  11. descriptionOptions: { service: 'Google' },
  12. name: 'Google',
  13. linkPath: '/auth/google',
  14. },
  15. orcid: {
  16. descriptionKey: 'oauth_orcid_description',
  17. descriptionOptions: {
  18. link: '/blog/434',
  19. appName: 'Overleaf',
  20. },
  21. name: 'ORCID',
  22. linkPath: '/auth/orcid',
  23. },
  24. twitter: {
  25. hideWhenNotLinked: true,
  26. name: 'Twitter',
  27. linkPath: '/auth/twitter',
  28. },
  29. }
  30. describe('SSOContext', function () {
  31. const renderSSOContext = () =>
  32. renderHook(() => useSSOContext(), {
  33. wrapper: ({ children }) => <SSOProvider>{children}</SSOProvider>,
  34. })
  35. beforeEach(function () {
  36. window.metaAttributesCache = new Map()
  37. window.metaAttributesCache.set('ol-thirdPartyIds', {
  38. google: 'google-id',
  39. })
  40. window.metaAttributesCache.set('ol-oauthProviders', mockOauthProviders)
  41. fetchMock.reset()
  42. })
  43. it('should initialise subscriptions with their linked status', function () {
  44. const { result } = renderSSOContext()
  45. expect(result.current.subscriptions).to.deep.equal({
  46. google: {
  47. providerId: 'google',
  48. provider: mockOauthProviders.google,
  49. linked: true,
  50. },
  51. orcid: {
  52. providerId: 'orcid',
  53. provider: mockOauthProviders.orcid,
  54. linked: false,
  55. },
  56. })
  57. })
  58. describe('unlink', function () {
  59. beforeEach(function () {
  60. fetchMock.post('express:/user/oauth-unlink', 200)
  61. })
  62. it('should unlink an existing subscription', async function () {
  63. const { result, waitForNextUpdate } = renderSSOContext()
  64. result.current.unlink('google')
  65. await waitForNextUpdate()
  66. expect(result.current.subscriptions.google.linked).to.be.false
  67. })
  68. it('when the provider is not linked, should do nothing', function () {
  69. const { result } = renderSSOContext()
  70. result.current.unlink('orcid')
  71. expect(fetchMock.called()).to.be.false
  72. })
  73. it('supports unmounting the component while the request is inflight', async function () {
  74. const { result, unmount } = renderSSOContext()
  75. result.current.unlink('google')
  76. expect(fetchMock.called()).to.be.true
  77. unmount()
  78. })
  79. })
  80. })