bootstrap.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { afterEach, beforeEach, chai, vi } from 'vitest'
  2. import 'sinon-mongoose'
  3. import sinon from 'sinon'
  4. import logger from '@overleaf/logger'
  5. import Metrics from '@overleaf/metrics'
  6. import sinonChai from 'sinon-chai'
  7. import chaiAsPromised from 'chai-as-promised'
  8. import mongoose from 'mongoose'
  9. import mongodb from 'mongodb-legacy'
  10. mongodb.ObjectId.cacheHexString = true
  11. /*
  12. * Chai configuration
  13. */
  14. // add chai.should()
  15. chai.should()
  16. // Load sinon-chai assertions so expect(stubFn).to.have.been.calledWith('abc')
  17. // has a nicer failure messages
  18. chai.use(sinonChai)
  19. // Load promise support for chai
  20. chai.use(chaiAsPromised)
  21. // Do not truncate assertion errors
  22. chai.config.truncateThreshold = 0
  23. vi.mock('@overleaf/logger', async () => {
  24. return {
  25. default: {
  26. debug: vi.fn(),
  27. info: vi.fn(),
  28. log: vi.fn(),
  29. warn: vi.fn(),
  30. err: vi.fn(),
  31. error: vi.fn(),
  32. fatal: vi.fn(),
  33. },
  34. }
  35. })
  36. // Mock metrics in unit tests, can be overridden
  37. vi.mock('@overleaf/metrics', () => {
  38. return {
  39. default: {
  40. inc: sinon.stub(),
  41. count: sinon.stub(),
  42. timing: sinon.stub(),
  43. summary: sinon.stub(),
  44. gauge: sinon.stub(),
  45. Timer: class {
  46. constructor() {
  47. this.labels = {}
  48. }
  49. done() {
  50. return 1
  51. }
  52. },
  53. prom: { Counter: sinon.stub(), Histogram: sinon.stub() },
  54. mongodb: { monitor: sinon.stub() },
  55. },
  56. }
  57. })
  58. beforeEach(ctx => {
  59. // This function is a utility to duplicate the behaviour of passing `done` in place of `next` in an express route handler.
  60. ctx.rejectOnError = reject => {
  61. return err => {
  62. if (err) {
  63. reject(err)
  64. }
  65. }
  66. }
  67. ctx.logger = logger
  68. ctx.Metrics = Metrics
  69. })
  70. afterEach(() => {
  71. vi.resetAllMocks()
  72. vi.resetModules()
  73. sinon.restore()
  74. sinon.resetHistory()
  75. const modelNames = mongoose.modelNames()
  76. modelNames.forEach(name => {
  77. delete mongoose.connection.models[name]
  78. })
  79. })