Unit Testing Marionette.Behaviors with mocha

634 Views Asked by At

Here is my behavior:

/**
 * @class Filter
 * @classdesc Holds filtering behavior for menu views
 * @extends Marionette.Behavior
 */
define(['marionette', 'eventer'], function (Marionette, eventer){
    'use strict';

    var Filter = Marionette.Behavior.extend({

        defaults: {
            field: "name"
        },

        initialize: function () {
            this.listenTo(eventer, 'menu:filter', this.onFilter, this);
        },

        /**
         * Checks each item's configured field_name (name, group_name, etc) to see if there are any
         * to show and to hide the non-matching terms
         * @method Filter.onFilter
         * @param {string} term
         */
        onFilter: function (term) {
            console.log(term);
            // if term is blank, render item
            if(term === "") {
                this.$el.show();
            }

            var pattern = new RegExp(term, "gi"),
                model = this.view.model,
                shouldShow = pattern.test(model.get(this.options.field));

            this.$el.toggle(shouldShow);
        }
    });

    return Filter;
});

Here is my test:

describe("#onFilter()", function () {
    it.only("should show the item based on the field and term passed in", function () {
        var view = new Marionette.ItemView({
                model: new Backbone.Model({ name: "foo", id: "1", checked: false, active_count: 10 }),
                template: under.template(templateHTML),
                tagName: 'article',
                behaviors: {
                    FilterBehavior: {
                        behaviorClass: FilterBehavior
                    }
                }
            });

        view.render();

        FilterBehavior.prototype.onFilter('foo');

        assert.equal(view.$el.css('display'), 'block');

        view.destroy();
    });
});

The error I keep getting is TypeError: 'undefined' is not an object (evaluating 'this.view.model'). Anyone know 1) Why this error is being thrown and 2) if this is the correct way to test a Marionette.Behavior?

1

There are 1 best solutions below

0
On

I can't say for sure, because I haven't tested it, but you're calling onFilter of the FilterBehavior prototype, which wouldn't have a view to reference.

Try view.trigger('filter', 'foo') instead.

Edit: this is a much older question that I thought it was