0
votes

So I've been following some tutorials about unit testing with Cloud Code. Here is how I organize my code base :

cloud/
  ChatMessage/
    model.js
    update.js
  ChatRoom/
    model.js
    update.js
test/
  test.js

In my model.js files, I have Parse.Object subclass with helper functions. It looks like this

class ChatMessage extends Parse.Object {
    constructor() {
        super('ChatMessage')
    }

    // Some functions
}

Parse.Object.registerSubclass('ChatMessage', ChatMessage)

module.exports = ChatMessage

In my update.js files, I have the before/after save and cloud code functions :

function beforeSave(request, response) {
    // Do stuff
}

Parse.Cloud.beforeSave('ChatMessage', function (request, response) {
    beforeSave(request, response)
})

module.exports = {
    beforeSave: beforeSave,
}

I've extracted the content of the beforeSave function for test purposes. It enables me to expose the before save function to mocha. For the record, all this works fine in production.

Now in my test I do this :

const ChatMessage = require('../cloud/ChatMessage/model.js')
const ChatMessageUpdate = require('../cloud/ChatMessage/update.js')
const expect = require('expect')

describe('ChatMessage', function () {
    const request = {
        user: new Parse.User(),
        object: new ChatMessage()
    }
    const response = {
        success: function () {},
        error: function () {}
    }

    describe('creation', function () {
        it('should fail when the author is undefined', function () {
            ChatMessageUpdate.beforeSave(request, response)
            expect(response.error).toHaveBeenCalled()
        })
    })
})

I mock the request and response object. And then I try to launch a test using my beforeSave function. And I get the following error :

class ChatRoom extends Parse.Object { ^

ReferenceError: Parse is not defined

A quick fix is to add this at the beginning of my model file like this : const Parse = require('parse/node')

But Parse is already expose in /cloud so it seems stupid to me to copy paste this line in every file. What should I do ? More precisely : how do I have my object oriented structure conform to tests ?

Also, what would be the best code structure to test all my code with zero asynchronous test (for test performance) ?

2

2 Answers

0
votes

You should define Parse in your test suite as a global

0
votes

Create a file in your test folder called helper.js that looks like this:

// helper.js
global.Parse = require('parse/node');

This should automatically get included in any of your tests. If you only have one test just add that line to the top of your test file.