lundi 2 mai 2016

How do you test Collection.allow( ) functions that rely on the user ID?

Given the following collection and access control defintion

class TasksCollection extends Mongo.Collection {
  insert (task, callback) {
    const doc = _.extend({}, task, {
      createdOn: new Date(),
      owner: this.userId
    })
    super.insert(doc, callback)
  }
}

export const Tasks = new TasksCollection('tasks')

// Simple checks to ensure that the user is logged in before making changes.
Tasks.allow({
  insert: (userId, doc) =>=> !!userId,
  update: (userId, doc, fields, modifier) => !!userId,
  remove: (userId, doc) => !!userId
})

How would you test to ensure that it works using Mocha/Chai/Sinon? This is what I have tried.

import { Meteor } from 'meteor/meteor'
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { assert, expect } from 'chai'
import { Tasks } from '/imports/api/tasks'
import sinon from 'sinon'

describe('collection test', () => {
  beforeEach(() => {
    resetDatabase()
  })
  it('can see a collection', () => {
    assert(Tasks, 'unable to see sample collection')
  })
  it('can query an empty collection', () => {
    expect(Tasks.find({}).fetch()).to.be.empty
  })
  it('can fail to add to a collection when the user is not logged in', () => {
    expect(Tasks.find({}).fetch()).to.be.empty
    expect(() => Tasks.insert({
      text: 'hello world'
    })).to.throw('unauthorized')
  })

  describe('logged in', () => {
    let sandbox
    beforeEach(() => {
      sandbox = sinon.sandbox.create()
      sandbox.stub(Meteor, 'userId').returns(42)
    })
    afterEach(()=> {
      sandbox.restore()
    })
    it('can add to a collection', () => {
      expect(Tasks.find({}).fetch()).to.be.empty
      Tasks.insert({
        text: 'hello world'
      })
      const results = Tasks.find({}).fetch()
      expect(results).to.have.lengthOf(1)
      expect(results[0].owner).to.equal(42)
      expect(results[0].createdOn).to.not.be.undefined
    })
  })
})

But I get expect(results[0].owner).to.equal(42) to fail and no exception is thrown when not logged in.

The insecure package is already removed.

I am only testing on the server for now as insert does not block on the client side.

Aucun commentaire:

Enregistrer un commentaire