chat-context.test.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // Disable prop type checks for test harnesses
  2. /* eslint-disable react/prop-types */
  3. import React from 'react'
  4. import { renderHook, act } from '@testing-library/react-hooks/dom'
  5. import { expect } from 'chai'
  6. import fetchMock from 'fetch-mock'
  7. import EventEmitter from 'events'
  8. import { useChatContext } from '../../../../../frontend/js/features/chat/context/chat-context'
  9. import {
  10. ChatProviders,
  11. cleanUpContext,
  12. } from '../../../helpers/render-with-context'
  13. import { stubMathJax, tearDownMathJaxStubs } from '../components/stubs'
  14. describe('ChatContext', function () {
  15. const user = {
  16. id: 'fake_user',
  17. first_name: 'fake_user_first_name',
  18. email: 'fake@example.com',
  19. }
  20. beforeEach(function () {
  21. fetchMock.reset()
  22. cleanUpContext()
  23. stubMathJax()
  24. })
  25. afterEach(function () {
  26. tearDownMathJaxStubs()
  27. })
  28. describe('socket connection', function () {
  29. beforeEach(function () {
  30. // Mock GET messages to return no messages
  31. fetchMock.get('express:/project/:projectId/messages', [])
  32. // Mock POST new message to return 200
  33. fetchMock.post('express:/project/:projectId/messages', 200)
  34. })
  35. it('subscribes when mounted', function () {
  36. const socket = new EventEmitter()
  37. renderChatContextHook({ user, socket })
  38. // Assert that there is 1 listener
  39. expect(socket.rawListeners('new-chat-message').length).to.equal(1)
  40. })
  41. it('unsubscribes when unmounted', function () {
  42. const socket = new EventEmitter()
  43. const { unmount } = renderChatContextHook({ user, socket })
  44. unmount()
  45. // Assert that there is 0 listeners
  46. expect(socket.rawListeners('new-chat-message').length).to.equal(0)
  47. })
  48. it('adds received messages to the list', async function () {
  49. // Mock socket: we only need to emit events, not mock actual connections
  50. const socket = new EventEmitter()
  51. const { result, waitForNextUpdate } = renderChatContextHook({
  52. user,
  53. socket,
  54. })
  55. // Wait until initial messages have loaded
  56. result.current.loadInitialMessages()
  57. await waitForNextUpdate()
  58. // No messages shown at first
  59. expect(result.current.messages).to.deep.equal([])
  60. // Mock message being received from another user
  61. socket.emit('new-chat-message', {
  62. id: 'msg_1',
  63. content: 'new message',
  64. timestamp: Date.now(),
  65. user: {
  66. id: 'another_fake_user',
  67. first_name: 'another_fake_user_first_name',
  68. email: 'another_fake@example.com',
  69. },
  70. })
  71. const message = result.current.messages[0]
  72. expect(message.id).to.equal('msg_1')
  73. expect(message.contents).to.deep.equal(['new message'])
  74. })
  75. it("doesn't add received messages from the current user if a message was just sent", async function () {
  76. const socket = new EventEmitter()
  77. const { result, waitForNextUpdate } = renderChatContextHook({
  78. user,
  79. socket,
  80. })
  81. // Wait until initial messages have loaded
  82. result.current.loadInitialMessages()
  83. await waitForNextUpdate()
  84. // Send a message from the current user
  85. result.current.sendMessage('sent message')
  86. // Receive a message from the current user
  87. socket.emit('new-chat-message', {
  88. id: 'msg_1',
  89. content: 'received message',
  90. timestamp: Date.now(),
  91. user,
  92. })
  93. // Expect that the sent message is shown, but the new message is not
  94. const messageContents = result.current.messages.map(
  95. ({ contents }) => contents[0]
  96. )
  97. expect(messageContents).to.include('sent message')
  98. expect(messageContents).to.not.include('received message')
  99. })
  100. it('adds the new message from the current user if another message was received after sending', async function () {
  101. const socket = new EventEmitter()
  102. const { result, waitForNextUpdate } = renderChatContextHook({
  103. user,
  104. socket,
  105. })
  106. // Wait until initial messages have loaded
  107. result.current.loadInitialMessages()
  108. await waitForNextUpdate()
  109. // Send a message from the current user
  110. result.current.sendMessage('sent message from current user')
  111. const [sentMessageFromCurrentUser] = result.current.messages
  112. expect(sentMessageFromCurrentUser.contents).to.deep.equal([
  113. 'sent message from current user',
  114. ])
  115. act(() => {
  116. // Receive a message from another user.
  117. socket.emit('new-chat-message', {
  118. id: 'msg_1',
  119. content: 'new message from other user',
  120. timestamp: Date.now(),
  121. user: {
  122. id: 'another_fake_user',
  123. first_name: 'another_fake_user_first_name',
  124. email: 'another_fake@example.com',
  125. },
  126. })
  127. })
  128. const [, messageFromOtherUser] = result.current.messages
  129. expect(messageFromOtherUser.contents).to.deep.equal([
  130. 'new message from other user',
  131. ])
  132. // Receive a message from the current user
  133. socket.emit('new-chat-message', {
  134. id: 'msg_2',
  135. content: 'received message from current user',
  136. timestamp: Date.now(),
  137. user,
  138. })
  139. // Since the current user didn't just send a message, it is now shown
  140. const [, , receivedMessageFromCurrentUser] = result.current.messages
  141. expect(receivedMessageFromCurrentUser.contents).to.deep.equal([
  142. 'received message from current user',
  143. ])
  144. })
  145. })
  146. describe('loadInitialMessages', function () {
  147. beforeEach(function () {
  148. fetchMock.get('express:/project/:projectId/messages', [
  149. {
  150. id: 'msg_1',
  151. content: 'a message',
  152. user,
  153. timestamp: Date.now(),
  154. },
  155. ])
  156. })
  157. it('adds messages to the list', async function () {
  158. const { result, waitForNextUpdate } = renderChatContextHook({ user })
  159. result.current.loadInitialMessages()
  160. await waitForNextUpdate()
  161. expect(result.current.messages[0].contents).to.deep.equal(['a message'])
  162. })
  163. it("won't load messages a second time", async function () {
  164. const { result, waitForNextUpdate } = renderChatContextHook({ user })
  165. result.current.loadInitialMessages()
  166. await waitForNextUpdate()
  167. expect(result.current.initialMessagesLoaded).to.equal(true)
  168. // Calling a second time won't do anything
  169. result.current.loadInitialMessages()
  170. expect(fetchMock.calls()).to.have.lengthOf(1)
  171. })
  172. })
  173. describe('loadMoreMessages', function () {
  174. it('adds messages to the list', async function () {
  175. // Mock a GET request for an initial message
  176. fetchMock.getOnce('express:/project/:projectId/messages', [
  177. {
  178. id: 'msg_1',
  179. content: 'first message',
  180. user,
  181. timestamp: new Date('2021-03-04T10:00:00').getTime(),
  182. },
  183. ])
  184. const { result, waitForNextUpdate } = renderChatContextHook({ user })
  185. result.current.loadMoreMessages()
  186. await waitForNextUpdate()
  187. expect(result.current.messages[0].contents).to.deep.equal([
  188. 'first message',
  189. ])
  190. // The before query param is not set
  191. expect(getLastFetchMockQueryParam('before')).to.be.null
  192. })
  193. it('adds more messages if called a second time', async function () {
  194. // Mock 2 GET requests, with different content
  195. fetchMock
  196. .getOnce(
  197. 'express:/project/:projectId/messages',
  198. // Resolve a full "page" of messages (50)
  199. createMessages(50, user, new Date('2021-03-04T10:00:00').getTime())
  200. )
  201. .getOnce(
  202. 'express:/project/:projectId/messages',
  203. [
  204. {
  205. id: 'msg_51',
  206. content: 'message from second page',
  207. user,
  208. timestamp: new Date('2021-03-04T11:00:00').getTime(),
  209. },
  210. ],
  211. { overwriteRoutes: false }
  212. )
  213. const { result, waitForNextUpdate } = renderChatContextHook({ user })
  214. result.current.loadMoreMessages()
  215. await waitForNextUpdate()
  216. // Call a second time
  217. result.current.loadMoreMessages()
  218. await waitForNextUpdate()
  219. // The second request is added to the list
  220. // Since both messages from the same user, they are collapsed into the
  221. // same "message"
  222. expect(result.current.messages[0].contents).to.include(
  223. 'message from second page'
  224. )
  225. // The before query param for the second request matches the timestamp
  226. // of the first message
  227. const beforeParam = parseInt(getLastFetchMockQueryParam('before'), 10)
  228. expect(beforeParam).to.equal(new Date('2021-03-04T10:00:00').getTime())
  229. })
  230. it("won't load more messages if there are no more messages", async function () {
  231. // Mock a GET request for 49 messages. This is less the the full page size
  232. // (50 messages), meaning that there are no further messages to be loaded
  233. fetchMock.getOnce(
  234. 'express:/project/:projectId/messages',
  235. createMessages(49, user)
  236. )
  237. const { result, waitForNextUpdate } = renderChatContextHook({ user })
  238. result.current.loadMoreMessages()
  239. await waitForNextUpdate()
  240. expect(result.current.messages[0].contents).to.have.length(49)
  241. result.current.loadMoreMessages()
  242. expect(result.current.atEnd).to.be.true
  243. expect(fetchMock.calls()).to.have.lengthOf(1)
  244. })
  245. it('handles socket messages while loading', async function () {
  246. // Mock GET messages so that we can control when the promise is resolved
  247. let resolveLoadingMessages
  248. fetchMock.get(
  249. 'express:/project/:projectId/messages',
  250. new Promise(resolve => {
  251. resolveLoadingMessages = resolve
  252. })
  253. )
  254. const socket = new EventEmitter()
  255. const { result, waitForNextUpdate } = renderChatContextHook({
  256. user,
  257. socket,
  258. })
  259. // Start loading messages
  260. result.current.loadMoreMessages()
  261. // Mock message being received from the socket while the request is in
  262. // flight
  263. socket.emit('new-chat-message', {
  264. id: 'socket_msg',
  265. content: 'socket message',
  266. timestamp: Date.now(),
  267. user: {
  268. id: 'another_fake_user',
  269. first_name: 'another_fake_user_first_name',
  270. email: 'another_fake@example.com',
  271. },
  272. })
  273. // Resolve messages being loaded
  274. resolveLoadingMessages([
  275. {
  276. id: 'fetched_msg',
  277. content: 'loaded message',
  278. user,
  279. timestamp: Date.now(),
  280. },
  281. ])
  282. await waitForNextUpdate()
  283. // Although the loaded message was resolved last, it appears first (since
  284. // requested messages must have come first)
  285. const messageContents = result.current.messages.map(
  286. ({ contents }) => contents[0]
  287. )
  288. expect(messageContents).to.deep.equal([
  289. 'loaded message',
  290. 'socket message',
  291. ])
  292. })
  293. })
  294. describe('sendMessage', function () {
  295. beforeEach(function () {
  296. // Mock GET messages to return no messages and POST new message to be
  297. // successful
  298. fetchMock
  299. .get('express:/project/:projectId/messages', [])
  300. .postOnce('express:/project/:projectId/messages', 200)
  301. })
  302. it('optimistically adds the message to the list', function () {
  303. const { result } = renderChatContextHook({ user })
  304. result.current.sendMessage('sent message')
  305. expect(result.current.messages[0].contents).to.deep.equal([
  306. 'sent message',
  307. ])
  308. })
  309. it('POSTs the message to the backend', function () {
  310. const { result } = renderChatContextHook({ user })
  311. result.current.sendMessage('sent message')
  312. const [, { body }] = fetchMock.lastCall(
  313. 'express:/project/:projectId/messages',
  314. 'POST'
  315. )
  316. expect(JSON.parse(body)).to.deep.equal({ content: 'sent message' })
  317. })
  318. it("doesn't send if the content is empty", function () {
  319. const { result } = renderChatContextHook({ user })
  320. result.current.sendMessage('')
  321. expect(result.current.messages).to.be.empty
  322. expect(
  323. fetchMock.called('express:/project/:projectId/messages', {
  324. method: 'post',
  325. })
  326. ).to.be.false
  327. })
  328. })
  329. describe('unread messages', function () {
  330. beforeEach(function () {
  331. // Mock GET messages to return no messages
  332. fetchMock.get('express:/project/:projectId/messages', [])
  333. })
  334. it('increments unreadMessageCount when a new message is received', function () {
  335. const socket = new EventEmitter()
  336. const { result } = renderChatContextHook({ user, socket })
  337. // Receive a new message from the socket
  338. socket.emit('new-chat-message', {
  339. id: 'msg_1',
  340. content: 'new message',
  341. timestamp: Date.now(),
  342. user,
  343. })
  344. expect(result.current.unreadMessageCount).to.equal(1)
  345. })
  346. it('resets unreadMessageCount when markMessagesAsRead is called', function () {
  347. const socket = new EventEmitter()
  348. const { result } = renderChatContextHook({ user, socket })
  349. // Receive a new message from the socket, incrementing unreadMessageCount
  350. // by 1
  351. socket.emit('new-chat-message', {
  352. id: 'msg_1',
  353. content: 'new message',
  354. timestamp: Date.now(),
  355. user,
  356. })
  357. result.current.markMessagesAsRead()
  358. expect(result.current.unreadMessageCount).to.equal(0)
  359. })
  360. })
  361. })
  362. function renderChatContextHook(props) {
  363. return renderHook(() => useChatContext(), {
  364. // Wrap with ChatContext.Provider (and the other editor context providers)
  365. // eslint-disable-next-line react/display-name
  366. wrapper: ({ children }) => (
  367. <ChatProviders {...props}>{children}</ChatProviders>
  368. ),
  369. })
  370. }
  371. function createMessages(number, user, timestamp = Date.now()) {
  372. return Array.from({ length: number }, (_m, idx) => ({
  373. id: `msg_${idx + 1}`,
  374. content: `message ${idx + 1}`,
  375. user,
  376. timestamp,
  377. }))
  378. }
  379. /*
  380. * Get query param by key from the last fetchMock response
  381. */
  382. function getLastFetchMockQueryParam(key) {
  383. const { url } = fetchMock.lastResponse()
  384. const { searchParams } = new URL(url, 'https://www.overleaf.com')
  385. return searchParams.get(key)
  386. }