ContactsManagerTests.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import sinon from 'sinon'
  2. import { expect } from 'chai'
  3. import esmock from 'esmock'
  4. import { ObjectId } from 'mongodb'
  5. describe('ContactManager', function () {
  6. beforeEach(async function () {
  7. this.clock = sinon.useFakeTimers(new Date())
  8. this.db = { contacts: {} }
  9. this.ContactManager = await esmock('../../../app/js/ContactManager', {
  10. '../../../app/js/mongodb': {
  11. db: this.db,
  12. ObjectId,
  13. },
  14. })
  15. this.user_id = new ObjectId().toString()
  16. this.contact_id = new ObjectId().toString()
  17. })
  18. afterEach(function () {
  19. this.clock.restore()
  20. })
  21. describe('touchContact', function () {
  22. beforeEach(function () {
  23. this.db.contacts.updateOne = sinon.stub().resolves()
  24. })
  25. describe('with a valid user_id', function () {
  26. it('should increment the contact count and timestamp', async function () {
  27. await expect(
  28. this.ContactManager.touchContact(this.user_id, 'mock_contact')
  29. ).not.to.be.rejected
  30. expect(this.db.contacts.updateOne).to.be.calledWith(
  31. {
  32. user_id: sinon.match(o => o.toString() === this.user_id),
  33. },
  34. {
  35. $inc: {
  36. 'contacts.mock_contact.n': 1,
  37. },
  38. $set: {
  39. 'contacts.mock_contact.ts': new Date(),
  40. },
  41. },
  42. {
  43. upsert: true,
  44. }
  45. )
  46. })
  47. })
  48. describe('with an invalid user id', function () {
  49. it('should be rejected', async function () {
  50. await expect(
  51. this.ContactManager.touchContact(
  52. 'not-valid-object-id',
  53. this.contact_id
  54. )
  55. ).to.be.rejectedWith(
  56. 'input must be a 24 character hex string, 12 byte Uint8Array, or an integer'
  57. )
  58. })
  59. })
  60. })
  61. describe('getContacts', function () {
  62. beforeEach(function () {
  63. this.user = {
  64. contacts: ['mock', 'contacts'],
  65. }
  66. this.db.contacts.findOne = sinon.stub().resolves(this.user)
  67. })
  68. describe('with a valid user_id', function () {
  69. it("should find the user's contacts", async function () {
  70. await expect(
  71. this.ContactManager.getContacts(this.user_id)
  72. ).to.eventually.deep.equal(this.user.contacts)
  73. expect(this.db.contacts.findOne).to.be.calledWith({
  74. user_id: sinon.match(o => o.toString() === this.user_id),
  75. })
  76. })
  77. })
  78. describe('with an invalid user id', function () {
  79. it('should be rejected', async function () {
  80. await expect(this.ContactManager.getContacts('not-valid-object-id')).to
  81. .be.rejected
  82. })
  83. })
  84. })
  85. })