<commit_before>FBL.ns(function() { with (FBL) {
// ************************************************************************************************

// ************************************************************************************************
// Console

var ConsoleAPI =
{
    firebuglite: Firebug.version,

    xxx: function(o)
    {
        var rep = Firebug.getRep(o);
        var className = "";

        var panel = Firebug.DOM.getPanel();
        var toggles = {};

        var row = Firebug.Console.getPanel().contentNode.ownerDocument.createElement("div");
        var target = row;
        var object = o;

        row.className = "logRow" + (className ? " logRow-"+className : "");
        //row.innerHTML = message.join("");

        rep.tag.replace({domPanel: panel, toggles: toggles, object: object}, target);

        Firebug.Console.appendRow(row);
    },

    log: function()
    {
        return Firebug.Console.logFormatted(arguments, "");
    },

    debug: function()
    {
        return Firebug.Console.logFormatted(arguments, "debug");
    },

    info: function()
    {
        return Firebug.Console.logFormatted(arguments, "info");
    },

    warn: function()
    {
        return Firebug.Console.logFormatted(arguments, "warning");
    },

    error: function()
    {
        return Firebug.Console.logFormatted(arguments, "error");
    },

    assert: function(truth, message)
    {
        if (!truth)
        {
            var args = [];
            for (var i = 1; i < arguments.length; ++i)
                args.push(arguments[i]);

            Firebug.Console.logFormatted(args.length ? args : ["Assertion Failure"], "error");
            throw message ? message : "Assertion Failure";
        }

        return Firebug.Console.LOG_COMMAND;
    },

    dir: function(object)
    {
        var html = [];

        var pairs = [];
        for (var name in object)
        {
            try
            {
                pairs.push([name, object[name]]);
            }
            catch (exc)
            {
            }
        }

        pairs.sort(function(a, b) { return a[0] < b[0] ? -1 : 1; });

        html.push('
');
        for (var i = 0; i < pairs.length; ++i)
        {
            var name = pairs[i][0], value = pairs[i][1];

            html.push('
',
                '
');

            Firebug.Reps.appendObject(value, html);

            html.push('

',
                escapeHTML(name), '
');

            html.push('
');
        }
        html.push('
');

        return Firebug.Console.logRow(html, "dir");
    },

    dirxml: function(node)
    {
        var html = [];

        Firebug.Reps.appendNode(node, html);
        return Firebug.Console.logRow(html, "dirxml");
    },

    group: function()
    {
        return Firebug.Console.logRow(arguments, "group", Firebug.Console.pushGroup);
    },

    groupEnd: function()
    {
        return Firebug.Console.logRow(arguments, "", Firebug.Console.popGroup);
    },

    time: function(name)
    {
        Firebug.Console.timeMap[name] = new Date().getTime();
        return Firebug.Console.LOG_COMMAND;
    },

    timeEnd: function(name)
    {
        var timeMap = Firebug.Console.timeMap;
        if (name in timeMap)
        {
            var delta = new Date().getTime() - timeMap[name];
            Firebug.Console.logFormatted([name+ ":", delta+"ms"]);
            delete timeMap[name];
        }
        return Firebug.Console.LOG_COMMAND;
    },

    count: function()
    {
        return this.warn(["count() not supported."]);
    },

    trace: function()
    {
        return this.warn(["trace() not supported."]);
    },

    profile: function()
    {
        return this.warn(["profile() not supported."]);
    },

    profileEnd: function()
    {
        return Firebug.Console.LOG_COMMAND;
    },

    clear: function()
    {
        Firebug.Console.getPanel().contentNode.innerHTML = "";
        return Firebug.Console.LOG_COMMAND;
    },

    open: function()
    {
        toggleConsole(true);
        return Firebug.Console.LOG_COMMAND;
    },

    close: function()
    {
        if (frameVisible)
            toggleConsole();

        return Firebug.Console.LOG_COMMAND;
    }
};

// ************************************************************************************************
// Console Module

var ConsoleModule = extend(Firebug.Module, ConsoleAPI);

Firebug.Console = extend(ConsoleModule,
{
    LOG_COMMAND: {},

    groupStack: [],
    timeMap: {},

    getPanel: function()
    {
        return Firebug.chrome ? Firebug.chrome.getPanel("Console") : null;
    },

    flush: function()
    {
        var queue = FirebugChrome.consoleMessageQueue;
        FirebugChrome.consoleMessageQueue = [];

        for (var i = 0; i < queue.length; ++i)
            this.writeMessage(queue[i][0], queue[i][1], queue[i][2]);
    },

    // ********************************************************************************************

    logFormatted: function(objects, className)
    {
        var html = [];

        var format = objects[0];
        var objIndex = 0;

        if (typeof(format) != "string")
        {
            format = "";
            objIndex = -1;
        }

        var parts = this.parseFormat(format);
        for (var i = 0; i < parts.length; ++i)
        {
            var part = parts[i];
            if (part && typeof(part) == "object")
            {
                var object = objects[++objIndex];
                part.appender(object, html);
            }
            else
                Firebug.Reps.appendText(part, html);
        }

        for (var i = objIndex+1; i < objects.length; ++i)
        {
            Firebug.Reps.appendText(" ", html);

            var object = objects[i];
            if (typeof(object) == "string")
                Firebug.Reps.appendText(object, html);
            else
                Firebug.Reps.appendObject(object, html);
        }

        return this.logRow(html, className);
    },

    parseFormat: function(format)
    {
        var parts = [];

        var reg = /((^%|[^\\]%)(\d+)?(\.)([a-zA-Z]))|((^%|[^\\]%)([a-zA-Z]))/;
        var Reps = Firebug.Reps;
        var appenderMap = {
                s: Reps.appendText,
                d: Reps.appendInteger,
                i: Reps.appendInteger,
                f: Reps.appendFloat
            };

        for (var m = reg.exec(format); m; m = reg.exec(format))
        {
            var type = m[8] ? m[8] : m[5];
            var appender = type in appenderMap ? appenderMap[type] : Reps.appendObject;
            var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0);

            parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1));
            parts.push({appender: appender, precision: precision});

            format = format.substr(m.index+m[0].length);
        }

        parts.push(format);

        return parts;
    },

    // ********************************************************************************************

    logRow: function(message, className, handler)
    {
        var panel = this.getPanel();

        if (panel && panel.contentNode)
            this.writeMessage(message, className, handler);
        else
        {
            FirebugChrome.consoleMessageQueue.push([message, className, handler]);
        }

        return this.LOG_COMMAND;
    },

    writeMessage: function(message, className, handler)
    {
        var container = this.getPanel().containerNode;
        var isScrolledToBottom =
            container.scrollTop + container.offsetHeight >= container.scrollHeight;

        if (!handler)
            handler = this.writeRow;

        handler.call(this, message, className);

        if (isScrolledToBottom)
            container.scrollTop = container.scrollHeight - container.offsetHeight;
    },

    appendRow: function(row)
    {
        if (this.groupStack.length > 0)
            var container = this.groupStack[this.groupStack.length-1];
        else
            var container = this.getPanel().contentNode;

        container.appendChild(row);
    },

    writeRow: function(message, className)
    {
        var row = this.getPanel().contentNode.ownerDocument.createElement("div");
        row.className = "logRow" + (className ? " logRow-"+className : "");
        row.innerHTML = message.join("");
        this.appendRow(row);
    },

    pushGroup: function(message, className)
    {
        this.logFormatted(message, className);

        var groupRow = this.getPanel().contentNode.ownerDocument.createElement("div");
        groupRow.className = "logGroup";
        var groupRowBox = this.getPanel().contentNode.ownerDocument.createElement("div");
        groupRowBox.className = "logGroupBox";
        groupRow.appendChild(groupRowBox);
        this.appendRow(groupRowBox);
        this.groupStack.push(groupRowBox);
    },

    popGroup: function()
    {
        this.groupStack.pop();
    }

});

Firebug.registerModule(Firebug.Console);

// ************************************************************************************************
// Console Panel

function ConsolePanel(){};

ConsolePanel.prototype = extend(Firebug.Panel,
{
    name: "Console",
    title: "Console",

    options:
    {
        hasCommandLine: true,
        hasToolButtons: true,
        isPreRendered: true,
        innerHTMLSync: true
    },

    create: function()
    {
        Firebug.Panel.create.apply(this, arguments);

        this.clearButton = new Firebug.Button({
            node: $("fbConsole_btClear"),
            owner: Firebug.Console,
            onClick: Firebug.Console.clear
        });
    },

    initialize: function()
    {
        Firebug.Panel.initialize.apply(this, arguments);

        this.clearButton.initialize();

        // TODO: xxxpedro
        if (Firebug.HTML)
        {
            addEvent($("fbPanel1"), 'mousemove', Firebug.HTML.onListMouseMove);
            addEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove);
            addEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove);
        }
    },

    shutdown: function()
    {
        // TODO: xxxpedro
        if (Firebug.HTML)
        {
            removeEvent($("fbPanel1"), 'mousemove', Firebug.HTML.onListMouseMove);
            removeEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove);
            removeEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove);
        }

        this.clearButton.shutdown();

        Firebug.Panel.shutdown.apply(this, arguments);
    }

});

Firebug.registerPanel(ConsolePanel);

// ************************************************************************************************

FBL.onError = function(msg, href, lineNo)
{
    var html = [];

    var lastSlash = href.lastIndexOf("/");
    var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1);

    html.push(
        '', msg, '',
        '
', fileName, ' (line ', lineNo, ')
'
    );

    Firebug.Console.logRow(html, "error");
};

// ************************************************************************************************
// Register console namespace

if (!isFirefox)
    Env.browser.window.console = ConsoleAPI;

// ************************************************************************************************
}});<commit_msg>Issue 394: implemented console.trace() provided by a contributor's patch (dongryphon).<commit_after>FBL.ns(function() { with (FBL) {
// ************************************************************************************************

// ************************************************************************************************
// Console

var ConsoleAPI =
{
    firebuglite: Firebug.version,

    xxx: function(o)
    {
        var rep = Firebug.getRep(o);
        var className = "";

        var panel = Firebug.DOM.getPanel();
        var toggles = {};

        var row = Firebug.Console.getPanel().contentNode.ownerDocument.createElement("div");
        var target = row;
        var object = o;

        row.className = "logRow" + (className ? " logRow-"+className : "");
        //row.innerHTML = message.join("");

        rep.tag.replace({domPanel: panel, toggles: toggles, object: object}, target);

        Firebug.Console.appendRow(row);
    },

    log: function()
    {
        return Firebug.Console.logFormatted(arguments, "");
    },

    debug: function()
    {
        return Firebug.Console.logFormatted(arguments, "debug");
    },

    info: function()
    {
        return Firebug.Console.logFormatted(arguments, "info");
    },

    warn: function()
    {
        return Firebug.Console.logFormatted(arguments, "warning");
    },

    error: function()
    {
        return Firebug.Console.logFormatted(arguments, "error");
    },

    assert: function(truth, message)
    {
        if (!truth)
        {
            var args = [];
            for (var i = 1; i < arguments.length; ++i)
                args.push(arguments[i]);

            Firebug.Console.logFormatted(args.length ? args : ["Assertion Failure"], "error");
            throw message ? message : "Assertion Failure";
        }

        return Firebug.Console.LOG_COMMAND;
    },

    dir: function(object)
    {
        var html = [];

        var pairs = [];
        for (var name in object)
        {
            try
            {
                pairs.push([name, object[name]]);
            }
            catch (exc)
            {
            }
        }

        pairs.sort(function(a, b) { return a[0] < b[0] ? -1 : 1; });

        html.push('
');
        for (var i = 0; i < pairs.length; ++i)
        {
            var name = pairs[i][0], value = pairs[i][1];

            html.push('
',
                '
');

            Firebug.Reps.appendObject(value, html);

            html.push('

',
                escapeHTML(name), '
');

            html.push('
');
        }
        html.push('
');

        return Firebug.Console.logRow(html, "dir");
    },

    dirxml: function(node)
    {
        var html = [];

        Firebug.Reps.appendNode(node, html);

        return Firebug.Console.logRow(html, "dirxml");
    },

    group: function()
    {
        return Firebug.Console.logRow(arguments, "group", Firebug.Console.pushGroup);
    },

    groupEnd: function()
    {
        return Firebug.Console.logRow(arguments, "", Firebug.Console.popGroup);
    },

    time: function(name)
    {
        Firebug.Console.timeMap[name] = new Date().getTime();

        return Firebug.Console.LOG_COMMAND;
    },

    timeEnd: function(name)
    {
        var timeMap = Firebug.Console.timeMap;

        if (name in timeMap)
        {
            var delta = new Date().getTime() - timeMap[name];
            Firebug.Console.logFormatted([name+ ":", delta+"ms"]);
            delete timeMap[name];
        }

        return Firebug.Console.LOG_COMMAND;
    },

    count: function()
    {
        return this.warn(["count() not supported."]);
    },

    trace: function()
    {
        var getFuncName = function getFuncName (f)
        {
            if (f.getName instanceof Function)
                return f.getName();
            if (f.name) // in FireFox, Function objects have a name property...
                return f.name;

            var name = f.toString().match(/function\s*(\w*)/)[1];
            return name || "anonymous";
        };

        var traceLabel = "Stack Trace";

        Firebug.Console.group(traceLabel);

        for (var fn = arguments.callee.caller; fn; fn = fn.caller)
        {
            var html = [ getFuncName(fn), "(" ];

            for (var i = 0, l = fn.arguments.length; i < l; ++i)
            {
                if (i)
                    html.push(", ");

                Firebug.Reps.appendObject(fn.arguments[i], html);
            }

            html.push(")");
            Firebug.Console.logRow(html, "stackTrace");
        }

        Firebug.Console.groupEnd(traceLabel);

        return Firebug.Console.LOG_COMMAND;
    },

    profile: function()
    {
        return this.warn(["profile() not supported."]);
    },

    profileEnd: function()
    {
        return this.warn(["profileEnd() not supported."]);
    },

    clear: function()
    {
        Firebug.Console.getPanel().contentNode.innerHTML = "";

        return Firebug.Console.LOG_COMMAND;
    },

    open: function()
    {
        toggleConsole(true);

        return Firebug.Console.LOG_COMMAND;
    },

    close: function()
    {
        if (frameVisible)
            toggleConsole();

        return Firebug.Console.LOG_COMMAND;
    }
};

// ************************************************************************************************
// Console Module

var ConsoleModule = extend(Firebug.Module, ConsoleAPI);

Firebug.Console = extend(ConsoleModule,
{
    LOG_COMMAND: {},

    groupStack: [],
    timeMap: {},

    getPanel: function()
    {
        return Firebug.chrome ? Firebug.chrome.getPanel("Console") : null;
    },

    flush: function()
    {
        var queue = FirebugChrome.consoleMessageQueue;
        FirebugChrome.consoleMessageQueue = [];

        for (var i = 0; i < queue.length; ++i)
            this.writeMessage(queue[i][0], queue[i][1], queue[i][2]);
    },

    // ********************************************************************************************

    logFormatted: function(objects, className)
    {
        var html = [];

        var format = objects[0];
        var objIndex = 0;

        if (typeof(format) != "string")
        {
            format = "";
            objIndex = -1;
        }

        var parts = this.parseFormat(format);
        for (var i = 0; i < parts.length; ++i)
        {
            var part = parts[i];
            if (part && typeof(part) == "object")
            {
                var object = objects[++objIndex];
                part.appender(object, html);
            }
            else
                Firebug.Reps.appendText(part, html);
        }

        for (var i = objIndex+1; i < objects.length; ++i)
        {
            Firebug.Reps.appendText(" ", html);

            var object = objects[i];
            if (typeof(object) == "string")
                Firebug.Reps.appendText(object, html);
            else
                Firebug.Reps.appendObject(object, html);
        }

        return this.logRow(html, className);
    },

    parseFormat: function(format)
    {
        var parts = [];

        var reg = /((^%|[^\\]%)(\d+)?(\.)([a-zA-Z]))|((^%|[^\\]%)([a-zA-Z]))/;
        var Reps = Firebug.Reps;
        var appenderMap = {
                s: Reps.appendText,
                d: Reps.appendInteger,
                i: Reps.appendInteger,
                f: Reps.appendFloat
            };

        for (var m = reg.exec(format); m; m = reg.exec(format))
        {
            var type = m[8] ? m[8] : m[5];
            var appender = type in appenderMap ? appenderMap[type] : Reps.appendObject;
            var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0);

            parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1));
            parts.push({appender: appender, precision: precision});

            format = format.substr(m.index+m[0].length);
        }

        parts.push(format);

        return parts;
    },

    // ********************************************************************************************

    logRow: function(message, className, handler)
    {
        var panel = this.getPanel();

        if (panel && panel.contentNode)
            this.writeMessage(message, className, handler);
        else
        {
            FirebugChrome.consoleMessageQueue.push([message, className, handler]);
        }

        return this.LOG_COMMAND;
    },

    writeMessage: function(message, className, handler)
    {
        var container = this.getPanel().containerNode;
        var isScrolledToBottom =
            container.scrollTop + container.offsetHeight >= container.scrollHeight;

        if (!handler)
            handler = this.writeRow;

        handler.call(this, message, className);

        if (isScrolledToBottom)
            container.scrollTop = container.scrollHeight - container.offsetHeight;
    },

    appendRow: function(row)
    {
        if (this.groupStack.length > 0)
            var container = this.groupStack[this.groupStack.length-1];
        else
            var container = this.getPanel().contentNode;

        container.appendChild(row);
    },

    writeRow: function(message, className)
    {
        var row = this.getPanel().contentNode.ownerDocument.createElement("div");
        row.className = "logRow" + (className ? " logRow-"+className : "");
        row.innerHTML = message.join("");
        this.appendRow(row);
    },

    pushGroup: function(message, className)
    {
        this.logFormatted(message, className);

        var groupRow = this.getPanel().contentNode.ownerDocument.createElement("div");
        groupRow.className = "logGroup";
        var groupRowBox = this.getPanel().contentNode.ownerDocument.createElement("div");
        groupRowBox.className = "logGroupBox";
        groupRow.appendChild(groupRowBox);
        this.appendRow(groupRowBox);
        this.groupStack.push(groupRowBox);
    },

    popGroup: function()
    {
        this.groupStack.pop();
    }

});

Firebug.registerModule(Firebug.Console);

// ************************************************************************************************
// Console Panel

function ConsolePanel(){};

ConsolePanel.prototype = extend(Firebug.Panel,
{
    name: "Console",
    title: "Console",

    options:
    {
        hasCommandLine: true,
        hasToolButtons: true,
        isPreRendered: true,
        innerHTMLSync: true
    },

    create: function()
    {
        Firebug.Panel.create.apply(this, arguments);

        this.clearButton = new Firebug.Button({
            node: $("fbConsole_btClear"),
            owner: Firebug.Console,
            onClick: Firebug.Console.clear
        });
    },

    initialize: function()
    {
        Firebug.Panel.initialize.apply(this, arguments);

        this.clearButton.initialize();

        // TODO: xxxpedro
        if (Firebug.HTML)
        {
            addEvent($("fbPanel1"), 'mousemove', Firebug.HTML.onListMouseMove);
            addEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove);
            addEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove);
        }
    },

    shutdown: function()
    {
        // TODO: xxxpedro
        if (Firebug.HTML)
        {
            removeEvent($("fbPanel1"), 'mousemove', Firebug.HTML.onListMouseMove);
            removeEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove);
            removeEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove);
        }

        this.clearButton.shutdown();

        Firebug.Panel.shutdown.apply(this, arguments);
    }

});

Firebug.registerPanel(ConsolePanel);

// ************************************************************************************************

FBL.onError = function(msg, href, lineNo)
{
    var html = [];

    var lastSlash = href.lastIndexOf("/");
    var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1);

    html.push(
        '', msg, '',
        '
', fileName, ' (line ', lineNo, ')
'
    );

    Firebug.Console.logRow(html, "error");
};

// ************************************************************************************************
// Register console namespace

if (!isFirefox)
    Env.browser.window.console = ConsoleAPI;

// ************************************************************************************************
}});<|endoftext|>


<commit_before>const expect = require('chai').expect
const urls = require('../lib/urls')
const baseurl = urls.baseurl

describe('urls', function() {
  it('urls.index()', function() {
    expect(urls.index()).to.equal(baseurl)
  })

  it('urls.full(path)', function() {
    expect(urls.full('')).to.equal('')
    expect(urls.full('/people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
    expect(urls.full('people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
    expect(urls.full('https://www.zhihu.com/people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
  })

  describe('urls.user', function() {
    it('urls.user.home(uname)', function() {
      expect(urls.user.home('test')).to
        .equal(baseurl + '/people/test')
    })

    it('urls.user.detail(uname)', function() {
      expect(urls.user.detail('test')).to
        .equal(baseurl + '/people/test/about')
    })

    it('urls.user.profile(uname)', function() {
      expect(urls.user.profile('test')).to
        .equal(baseurl + '/node/MemberProfileCardV2?params=%7B%22url_token%22%3A%22test%22%7D')
    })

    it('urls.user.followers()', function() {
      expect(urls.user.followers()).to
        .equal(baseurl + '/node/ProfileFollowersListV2')
    })

    it('urls.user.followees()', function() {
      expect(urls.user.followees()).to
        .equal(baseurl + '/node/ProfileFolloweesListV2')
    })

    it('urls.user.questions(uname, page)', function() {
      expect(urls.user.questions('test', 1)).to
        .equal(baseurl + '/people/test/asks?page=1')
    })

    it('urls.user.answers(uname, page)', function() {
      expect(urls.user.answers('test', 1)).to
        .equal(baseurl + '/people/test/answers?page=1')
    })

    it('urls.user.posts(uname)', function() {
      expect(urls.user.posts('test')).to
        .equal(baseurl + '/people/test/posts?page=1')
    })

    it('urls.user.collections(uname, page)', function() {
      expect(urls.user.collections('test')).to
        .equal(baseurl + '/people/test/collections?page=1')
    })

    it('urls.user.topics(uname)', function() {
      expect(urls.user.topics('test')).to
        .equal(baseurl + '/people/test/topics')
    })

    it('urls.user.columns()', function() {
      expect(urls.user.columns()).to
        .equal(baseurl + '/node/ProfileFollowedColumnsListV2')
    })

    it('urls.user.activities(uname)', function() {
      expect(urls.user.activities('test')).to
        .equal(baseurl + '/people/test/activities')
    })
  })

  describe('urls.question', function() {
    it('urls.question.home(id)', function() {
      expect(urls.question.home(1234567)).to
        .equal(baseurl + '/question/1234567')
    })

    it('urls.question.answersByVote()', function() {
      expect(urls.question.answersByVote()).to
        .equal(baseurl + '/node/QuestionAnswerListV2')
    })

    it('urls.question.answersByPage(id, page)', function() {
      expect(urls.question.answersByPage(41325553)).to
        .equal(baseurl + '/question/41325553?sort=created&page=1')

      expect(urls.question.answersByPage(41325553, 2)).to
        .equal(baseurl + '/question/41325553?sort=created&page=2')
    })

    it('urls.question.followers(id)', function() {
      expect(urls.question.followers(1234567)).to
        .equal(baseurl + '/question/1234567/followers')
    })
  })

  describe('urls.answer', function() {
    it('urls.answer.voters(aid)', function() {
      expect(urls.answer.voters(1234567)).to
        .equal(baseurl + '/answer/1234567/voters_profile')
    })

    it('urls.answer.comments(aid, page)', function() {
      expect(urls.answer.comments(1234567)).to
        .equal(baseurl + '/r/answers/1234567/comments?page=1')

      expect(urls.answer.comments(1234567, 2)).to
        .equal(baseurl + '/r/answers/1234567/comments?page=2')
    })

    it('urls.answer.explore(offset, type)', function() {
      expect(urls.answer.explore(10, 'day')).to
        .equal(baseurl + '/node/ExploreAnswerListV2?params={"offset":10,"type":"day"}')

      expect(urls.answer.explore(10, 'month')).to
        .equal(baseurl + '/node/ExploreAnswerListV2?params={"offset":10,"type":"month"}')
    })
  })

  describe('urls.action', function() {
    it('urls.action.follow()', function() {
      expect(urls.action.follow()).to
        .equal(baseurl + '/node/MemberFollowBaseV2')
    })

    it('urls.action.followTopic()', function() {
      expect(urls.action.followTopic()).to
        .equal(baseurl + '/node/TopicFollowBaseV2')
    })

    it('urls.action.followQuestion()', function() {
      expect(urls.action.followQuestion()).to
        .equal(baseurl + '/node/QuestionFollowBaseV2')
    })

    it('urls.action.voteAnswer()', function() {
      expect(urls.action.voteAnswer()).to
        .equal(baseurl + '/node/AnswerVoteBarV2')
    })

    it('urls.action.sendMessage()', function() {
      expect(urls.action.sendMessage()).to
        .equal(baseurl + '/inbox/post')
    })

    it('urls.action.block(uname)', function() {
      expect(urls.action.block('test')).to
        .equal(baseurl + '/people/test/block')
    })
  })

  describe('urls.topic', function() {
    it('urls.topic.organize(id)', function() {
      expect(urls.topic.organize(1234567)).to
        .equal(baseurl + '/topic/1234567/organize')
    })

    it('urls.topic.followers(id)', function() {
      expect(urls.topic.followers(1234567)).to
        .equal(baseurl + '/topic/1234567/followers')
    })

    it('urls.topic.topAnswers(id, page)', function() {
      expect(urls.topic.topAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/top-answers?page=1')

      expect(urls.topic.topAnswers(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/top-answers?page=2')
    })

    it('urls.topic.hotAnswers(id)', function() {
      expect(urls.topic.hotAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/hot')
    })

    it('urls.topic.newAnswers(id)', function() {
      expect(urls.topic.newAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/newest')
    })

    it('urls.topic.pendingQuestions(id)', function() {
      expect(urls.topic.pendingQuestions(1234567)).to
        .equal(baseurl + '/topic/1234567/questions?page=1')

      expect(urls.topic.pendingQuestions(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/questions?page=2')
    })

    it('urls.topic.hotPendingQuestions(id)', function() {
      expect(urls.topic.hotPendingQuestions(1234567)).to
        .equal(baseurl + '/topic/1234567/unanswered?page=1')

      expect(urls.topic.hotPendingQuestions(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/unanswered?page=2')
    })
  })
})
<commit_msg>update config<commit_after>const expect = require('chai').expect
const assert = require('assert')
const urls = require('../lib/urls')
const baseurl = urls.baseurl

describe('urls', function() {
  it('urls.index()', function() {
    assert(url.index() === baseurl)
  })

  it('urls.full(path)', function() {
    expect(urls.full('')).to.equal('')
    expect(urls.full('/people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
    expect(urls.full('people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
    expect(urls.full('https://www.zhihu.com/people/zhihuadmin')).to.equal(baseurl + '/people/zhihuadmin')
  })

  describe('urls.user', function() {
    it('urls.user.home(uname)', function() {
      expect(urls.user.home('test')).to
        .equal(baseurl + '/people/test')
    })

    it('urls.user.detail(uname)', function() {
      expect(urls.user.detail('test')).to
        .equal(baseurl + '/people/test/about')
    })

    it('urls.user.profile(uname)', function() {
      expect(urls.user.profile('test')).to
        .equal(baseurl + '/node/MemberProfileCardV2?params=%7B%22url_token%22%3A%22test%22%7D')
    })

    it('urls.user.followers()', function() {
      expect(urls.user.followers()).to
        .equal(baseurl + '/node/ProfileFollowersListV2')
    })

    it('urls.user.followees()', function() {
      expect(urls.user.followees()).to
        .equal(baseurl + '/node/ProfileFolloweesListV2')
    })

    it('urls.user.questions(uname, page)', function() {
      expect(urls.user.questions('test', 1)).to
        .equal(baseurl + '/people/test/asks?page=1')
    })

    it('urls.user.answers(uname, page)', function() {
      expect(urls.user.answers('test', 1)).to
        .equal(baseurl + '/people/test/answers?page=1')
    })

    it('urls.user.posts(uname)', function() {
      expect(urls.user.posts('test')).to
        .equal(baseurl + '/people/test/posts?page=1')
    })

    it('urls.user.collections(uname, page)', function() {
      expect(urls.user.collections('test')).to
        .equal(baseurl + '/people/test/collections?page=1')
    })

    it('urls.user.topics(uname)', function() {
      expect(urls.user.topics('test')).to
        .equal(baseurl + '/people/test/topics')
    })

    it('urls.user.columns()', function() {
      expect(urls.user.columns()).to
        .equal(baseurl + '/node/ProfileFollowedColumnsListV2')
    })

    it('urls.user.activities(uname)', function() {
      expect(urls.user.activities('test')).to
        .equal(baseurl + '/people/test/activities')
    })
  })

  describe('urls.question', function() {
    it('urls.question.home(id)', function() {
      expect(urls.question.home(1234567)).to
        .equal(baseurl + '/question/1234567')
    })

    it('urls.question.answersByVote()', function() {
      expect(urls.question.answersByVote()).to
        .equal(baseurl + '/node/QuestionAnswerListV2')
    })

    it('urls.question.answersByPage(id, page)', function() {
      expect(urls.question.answersByPage(41325553)).to
        .equal(baseurl + '/question/41325553?sort=created&page=1')

      expect(urls.question.answersByPage(41325553, 2)).to
        .equal(baseurl + '/question/41325553?sort=created&page=2')
    })

    it('urls.question.followers(id)', function() {
      expect(urls.question.followers(1234567)).to
        .equal(baseurl + '/question/1234567/followers')
    })
  })

  describe('urls.answer', function() {
    it('urls.answer.voters(aid)', function() {
      expect(urls.answer.voters(1234567)).to
        .equal(baseurl + '/answer/1234567/voters_profile')
    })

    it('urls.answer.comments(aid, page)', function() {
      expect(urls.answer.comments(1234567)).to
        .equal(baseurl + '/r/answers/1234567/comments?page=1')

      expect(urls.answer.comments(1234567, 2)).to
        .equal(baseurl + '/r/answers/1234567/comments?page=2')
    })

    it('urls.answer.explore(offset, type)', function() {
      expect(urls.answer.explore(10, 'day')).to
        .equal(baseurl + '/node/ExploreAnswerListV2?params={"offset":10,"type":"day"}')

      expect(urls.answer.explore(10, 'month')).to
        .equal(baseurl + '/node/ExploreAnswerListV2?params={"offset":10,"type":"month"}')
    })
  })

  describe('urls.action', function() {
    it('urls.action.follow()', function() {
      expect(urls.action.follow()).to
        .equal(baseurl + '/node/MemberFollowBaseV2')
    })

    it('urls.action.followTopic()', function() {
      expect(urls.action.followTopic()).to
        .equal(baseurl + '/node/TopicFollowBaseV2')
    })

    it('urls.action.followQuestion()', function() {
      expect(urls.action.followQuestion()).to
        .equal(baseurl + '/node/QuestionFollowBaseV2')
    })

    it('urls.action.voteAnswer()', function() {
      expect(urls.action.voteAnswer()).to
        .equal(baseurl + '/node/AnswerVoteBarV2')
    })

    it('urls.action.sendMessage()', function() {
      expect(urls.action.sendMessage()).to
        .equal(baseurl + '/inbox/post')
    })

    it('urls.action.block(uname)', function() {
      expect(urls.action.block('test')).to
        .equal(baseurl + '/people/test/block')
    })
  })

  describe('urls.topic', function() {
    it('urls.topic.organize(id)', function() {
      expect(urls.topic.organize(1234567)).to
        .equal(baseurl + '/topic/1234567/organize')
    })

    it('urls.topic.followers(id)', function() {
      expect(urls.topic.followers(1234567)).to
        .equal(baseurl + '/topic/1234567/followers')
    })

    it('urls.topic.topAnswers(id, page)', function() {
      expect(urls.topic.topAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/top-answers?page=1')

      expect(urls.topic.topAnswers(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/top-answers?page=2')
    })

    it('urls.topic.hotAnswers(id)', function() {
      expect(urls.topic.hotAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/hot')
    })

    it('urls.topic.newAnswers(id)', function() {
      expect(urls.topic.newAnswers(1234567)).to
        .equal(baseurl + '/topic/1234567/newest')
    })

    it('urls.topic.pendingQuestions(id)', function() {
      expect(urls.topic.pendingQuestions(1234567)).to
        .equal(baseurl + '/topic/1234567/questions?page=1')

      expect(urls.topic.pendingQuestions(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/questions?page=2')
    })

    it('urls.topic.hotPendingQuestions(id)', function() {
      expect(urls.topic.hotPendingQuestions(1234567)).to
        .equal(baseurl + '/topic/1234567/unanswered?page=1')

      expect(urls.topic.hotPendingQuestions(1234567, 2)).to
        .equal(baseurl + '/topic/1234567/unanswered?page=2')
    })
  })
})
<|endoftext|>


<commit_before>import Service from '@ember/service';
import EmberObject from '@ember/object';
import { resolve } from 'rsvp';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click, find, findAll, fillIn } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { run } from '@ember/runloop';

const permissionCheckerMock = Service.extend({
  async canCreateUser() {
    return resolve(true);
  }
});

module('Integration | Component | new directory user', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(async function () {
    const schools = this.server.createList('school', 3);
    const user = this.server.create('user', {
      school: schools[0]
    });
    const userModel = await run(() => this.owner.lookup('service:store').find('user', user.id));
    const currentUserMock = Service.extend({
      model: resolve(userModel)
    });

    this.owner.register('service:current-user', currentUserMock);
    this['current-user'] = this.owner.lookup('service:current-user');
    this.owner.register('service:permissionChecker', permissionCheckerMock);
  });

  test('it renders', async function(assert) {
    this.set('nothing', () => {});

    await render(hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action nothing)}}`);
    assert.ok(this.element.textContent.includes('Search directory for new users'));
  });

  test('input into the search field fires action', async function(assert) {
    assert.expect(1);
    const searchTerm = 'search for me!';
    this.set('nothing', parseInt);
    this.set('setSearchTerms', (val)=>{
      assert.equal(val, searchTerm, 'changes to search get sent as action');
    });
    await render(
      hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action setSearchTerms) searchTerms=startingSearchTerms}}`
    );
    const searchBox = '.new-directory-user-search-tools';
    const searchInput = `${searchBox} input`;
    await fillIn(searchInput, searchTerm);
  });

  test('initial search input fires search and fills input', async function(assert) {
    assert.expect(2);
    const startingSearchTerms = 'start here';

    let ajaxMock = Service.extend({
      request(url){
        assert.equal(url.trim(), `/application/directory/search?limit=51&searchTerms=${startingSearchTerms}`);
        return resolve({
          results: []
        });
      }
    });
    this.owner.register('service:commonAjax', ajaxMock);
    this.set('nothing', parseInt);
    this.set('startingSearchTerms', startingSearchTerms);
    await render(
      hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action nothing) searchTerms=startingSearchTerms}}`
    );
    const searchBox = '.new-directory-user-search-tools';
    const searchInput = `${searchBox} input`;
    assert.equal(find(searchInput).value, startingSearchTerms, 'passed value is in the box');

  });

  test('create new user', async function(assert) {
    assert.expect(32);
    this.server.create('user-role', {
      id: 4,
      title: 'Student'
    });
    const user1Object = EmberObject.create('user', {
      firstName: 'user1-first',
      lastName: 'user1-last',
      campusId: 'user1-campus',
      email: 'user1@test.com',
      telephoneNumber: 'user11234',
      user: null,
      username: 'user1-username',
    });
    const user2Object = EmberObject.create('user', {
      firstName: 'user2-first',
      lastName: 'user2-last',
      campusId: 'user2-campus',
      email: 'user2@test.com',
      telephoneNumber: 'user21234',
      user: 4136,
      username: 'user2-username',
    });
    const user3Object = EmberObject.create('user', {
      firstName: 'user3-first',
      lastName: 'user3-last',
      campusId: null,
      email: null,
      telephoneNumber: 'user31234',
      user: null,
      username: null,
    });
    this.server.create('user', user1Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    const user2 = this.server.create('user', user2Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    this.server.create('authentication', {
      user: user2,
      username: user2.username,
    });
    this.server.create('user', user3Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    let ajaxRequestCalled = 0;

    const ajaxMock = Service.extend({
      request(url){
        ajaxRequestCalled++;
        if (ajaxRequestCalled === 1){
          assert.equal(url.trim(), '/application/directory/search?limit=51&searchTerms=searchterm', 'search for user request is correct');
          return resolve({
            results: [user1Object, user2Object, user3Object]
          });
        }
        if (ajaxRequestCalled === 2){
          assert.equal(url.trim(), '/application/config', 'config request is correct');
          return resolve({config: {
            locale: 'en',
            type: 'ladp',
            userSearchType: 'ldap',
          }});
        }

      }
    });
    this.owner.register('service:commonAjax', ajaxMock);

    this.set('nothing', parseInt);
    this.set('transitionToUser', (userId)=>{
      assert.equal(userId, 5, 'after saving we transition to the right user');
    });
    await render(hbs`{{new-directory-user
      close=(action nothing)
      setSearchTerms=(action nothing)
      transitionToUser=(action transitionToUser)
      searchTerms='searchterm'
    }}`);

    const results = '.new-directory-user-search-results';
    const firstResultValues = `${results} tbody tr:nth-of-type(1) td`;
    const secondResultValues = `${results} tbody tr:nth-of-type(2) td`;
    const thirdResultValues = `${results} tbody tr:nth-of-type(3) td`;
    const firstIcon = `${firstResultValues}:nth-of-type(1) svg`;
    const secondIcon = `${secondResultValues}:nth-of-type(1) svg`;
    const thirdIcon = `${thirdResultValues}:nth-of-type(1) svg`;

    const firstName = '[data-test-first-name] span';
    const lastName = '[data-test-last-name] span';
    const campusId = '[data-test-campus-id] span';
    const email = '[data-test-email] span';
    const phone = '[data-test-phone] span';
    const otherId = '[data-test-other-id] input';
    const username = '[data-test-username] span';

    const save = '.done';

    assert.ok(find(firstIcon).classList.contains('fa-plus'), 'this user can be added');
    assert.equal(findAll(firstResultValues)[1].textContent.trim(), user1Object.get('firstName') + ' ' + user1Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(firstResultValues)[2].textContent.trim(), user1Object.get('campusId'), 'correct display for campusId');
    assert.equal(findAll(firstResultValues)[3].textContent.trim(), user1Object.get('email'), 'correct display for email');

    assert.ok(find(secondIcon).classList.contains('fa-sun'), 'correct display for things');
    assert.equal(findAll(secondResultValues)[1].textContent.trim(), user2Object.get('firstName') + ' ' + user2Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(secondResultValues)[2].textContent.trim(), user2Object.get('campusId'), 'correct display for campusId');
    assert.equal(findAll(secondResultValues)[3].textContent.trim(), user2Object.get('email'), 'correct display for email');

    assert.ok(find(thirdIcon).classList.contains('fa-ambulance'), 'correct display for things');
    assert.equal(findAll(thirdResultValues)[1].textContent.trim(), user3Object.get('firstName') + ' ' + user3Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(thirdResultValues)[2].textContent.trim(), '', 'campus id is empty');
    assert.equal(findAll(thirdResultValues)[3].textContent.trim(), '', 'email is empty');

    await click(firstIcon);

    assert.equal(find(firstName).textContent.trim(), user1Object.get('firstName'), 'firstName is correct in form');
    assert.equal(find(lastName).textContent.trim(), user1Object.get('lastName'), 'lastName is correct in form');
    assert.equal(find(campusId).textContent.trim(), user1Object.get('campusId'), 'campusId is correct in form');
    assert.equal(find(email).textContent.trim(), user1Object.get('email'), 'email is correct in form');
    assert.equal(find(phone).textContent.trim(), user1Object.get('telephoneNumber'), 'phone is correct in form');
    assert.equal(find(otherId).textContent.trim(), '', 'otherId is blank in form');
    assert.equal(find(username).textContent.trim(), user1Object.get('username'), 'username is correct in form');

    await click(save);

    const userModel = await run(() => this.owner.lookup('service:store').find('user', 5));
    assert.equal(userModel.firstName, user1Object.get('firstName'), 'record created with correct value for firstName');
    assert.equal(userModel.middleName, null, 'record created with correct value for middleName');
    assert.equal(userModel.lastName, user1Object.get('lastName'), 'record created with correct value for lastName');
    assert.equal(userModel.campusId, user1Object.get('campusId'), 'record created with correct value for campusId');
    assert.equal(userModel.otherId, null, 'record created with correct value for otherId');
    assert.equal(userModel.phone, user1Object.get('telephoneNumber'), 'record created with correct value for phone');
    assert.equal(userModel.email, user1Object.get('email'), 'record created with correct value for email');

    const authenticationModel = await run(() => this.owner.lookup('service:store').find('authentication', 2));
    assert.equal(authenticationModel.username, user1Object.get('username'), 'record has correct username');
    assert.equal(authenticationModel.password, null, 'record has no password');
    assert.equal(authenticationModel.user.get('id'), '5', 'we are linking to the expected user');
  });
});
<commit_msg>Fix test data<commit_after>import Service from '@ember/service';
import EmberObject from '@ember/object';
import { resolve } from 'rsvp';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click, find, findAll, fillIn } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { run } from '@ember/runloop';

const permissionCheckerMock = Service.extend({
  async canCreateUser() {
    return resolve(true);
  }
});

module('Integration | Component | new directory user', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(async function () {
    const schools = this.server.createList('school', 3);
    const user = this.server.create('user', {
      school: schools[0]
    });
    const userModel = await run(() => this.owner.lookup('service:store').find('user', user.id));
    const currentUserMock = Service.extend({
      model: resolve(userModel)
    });

    this.owner.register('service:current-user', currentUserMock);
    this['current-user'] = this.owner.lookup('service:current-user');
    this.owner.register('service:permissionChecker', permissionCheckerMock);
  });

  test('it renders', async function(assert) {
    this.set('nothing', () => {});

    await render(hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action nothing)}}`);
    assert.ok(this.element.textContent.includes('Search directory for new users'));
  });

  test('input into the search field fires action', async function(assert) {
    assert.expect(1);
    const searchTerm = 'search for me!';
    this.set('nothing', parseInt);
    this.set('setSearchTerms', (val)=>{
      assert.equal(val, searchTerm, 'changes to search get sent as action');
    });
    await render(
      hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action setSearchTerms) searchTerms=startingSearchTerms}}`
    );
    const searchBox = '.new-directory-user-search-tools';
    const searchInput = `${searchBox} input`;
    await fillIn(searchInput, searchTerm);
  });

  test('initial search input fires search and fills input', async function(assert) {
    assert.expect(2);
    const startingSearchTerms = 'start here';

    let ajaxMock = Service.extend({
      request(url){
        assert.equal(url.trim(), `/application/directory/search?limit=51&searchTerms=${startingSearchTerms}`);
        return resolve({
          results: []
        });
      }
    });
    this.owner.register('service:commonAjax', ajaxMock);
    this.set('nothing', parseInt);
    this.set('startingSearchTerms', startingSearchTerms);
    await render(
      hbs`{{new-directory-user close=(action nothing) setSearchTerms=(action nothing) searchTerms=startingSearchTerms}}`
    );
    const searchBox = '.new-directory-user-search-tools';
    const searchInput = `${searchBox} input`;
    assert.equal(find(searchInput).value, startingSearchTerms, 'passed value is in the box');

  });

  test('create new user', async function(assert) {
    assert.expect(32);
    this.server.create('user-role', {
      id: 4,
      title: 'Student'
    });
    const user1Object = EmberObject.create({
      firstName: 'user1-first',
      lastName: 'user1-last',
      campusId: 'user1-campus',
      email: 'user1@test.com',
      telephoneNumber: 'user11234',
      user: null,
      username: 'user1-username',
    });
    const user2Object = EmberObject.create({
      firstName: 'user2-first',
      lastName: 'user2-last',
      campusId: 'user2-campus',
      email: 'user2@test.com',
      telephoneNumber: 'user21234',
      user: 4136,
      username: 'user2-username',
    });
    const user3Object = EmberObject.create({
      firstName: 'user3-first',
      lastName: 'user3-last',
      campusId: null,
      email: null,
      telephoneNumber: 'user31234',
      user: null,
      username: null,
    });
    this.server.create('user', user1Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    const user2 = this.server.create('user', user2Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    this.server.create('authentication', {
      user: user2,
      username: user2Object.username,
    });
    this.server.create('user', user3Object.getProperties('firstName', 'lastName', 'campusId', 'email', 'telephoneNumber'));
    let ajaxRequestCalled = 0;

    const ajaxMock = Service.extend({
      request(url){
        ajaxRequestCalled++;
        if (ajaxRequestCalled === 1){
          assert.equal(url.trim(), '/application/directory/search?limit=51&searchTerms=searchterm', 'search for user request is correct');
          return resolve({
            results: [user1Object, user2Object, user3Object]
          });
        }
        if (ajaxRequestCalled === 2){
          assert.equal(url.trim(), '/application/config', 'config request is correct');
          return resolve({config: {
            locale: 'en',
            type: 'ladp',
            userSearchType: 'ldap',
          }});
        }

      }
    });
    this.owner.register('service:commonAjax', ajaxMock);

    this.set('nothing', parseInt);
    this.set('transitionToUser', (userId)=>{
      assert.equal(userId, 5, 'after saving we transition to the right user');
    });
    await render(hbs`{{new-directory-user
      close=(action nothing)
      setSearchTerms=(action nothing)
      transitionToUser=(action transitionToUser)
      searchTerms='searchterm'
    }}`);

    const results = '.new-directory-user-search-results';
    const firstResultValues = `${results} tbody tr:nth-of-type(1) td`;
    const secondResultValues = `${results} tbody tr:nth-of-type(2) td`;
    const thirdResultValues = `${results} tbody tr:nth-of-type(3) td`;
    const firstIcon = `${firstResultValues}:nth-of-type(1) svg`;
    const secondIcon = `${secondResultValues}:nth-of-type(1) svg`;
    const thirdIcon = `${thirdResultValues}:nth-of-type(1) svg`;

    const firstName = '[data-test-first-name] span';
    const lastName = '[data-test-last-name] span';
    const campusId = '[data-test-campus-id] span';
    const email = '[data-test-email] span';
    const phone = '[data-test-phone] span';
    const otherId = '[data-test-other-id] input';
    const username = '[data-test-username] span';

    const save = '.done';

    assert.ok(find(firstIcon).classList.contains('fa-plus'), 'this user can be added');
    assert.equal(findAll(firstResultValues)[1].textContent.trim(), user1Object.get('firstName') + ' ' + user1Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(firstResultValues)[2].textContent.trim(), user1Object.get('campusId'), 'correct display for campusId');
    assert.equal(findAll(firstResultValues)[3].textContent.trim(), user1Object.get('email'), 'correct display for email');

    assert.ok(find(secondIcon).classList.contains('fa-sun'), 'correct display for things');
    assert.equal(findAll(secondResultValues)[1].textContent.trim(), user2Object.get('firstName') + ' ' + user2Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(secondResultValues)[2].textContent.trim(), user2Object.get('campusId'), 'correct display for campusId');
    assert.equal(findAll(secondResultValues)[3].textContent.trim(), user2Object.get('email'), 'correct display for email');

    assert.ok(find(thirdIcon).classList.contains('fa-ambulance'), 'correct display for things');
    assert.equal(findAll(thirdResultValues)[1].textContent.trim(), user3Object.get('firstName') + ' ' + user3Object.get('lastName'), 'correct display for name');
    assert.equal(findAll(thirdResultValues)[2].textContent.trim(), '', 'campus id is empty');
    assert.equal(findAll(thirdResultValues)[3].textContent.trim(), '', 'email is empty');

    await click(firstIcon);

    assert.equal(find(firstName).textContent.trim(), user1Object.get('firstName'), 'firstName is correct in form');
    assert.equal(find(lastName).textContent.trim(), user1Object.get('lastName'), 'lastName is correct in form');
    assert.equal(find(campusId).textContent.trim(), user1Object.get('campusId'), 'campusId is correct in form');
    assert.equal(find(email).textContent.trim(), user1Object.get('email'), 'email is correct in form');
    assert.equal(find(phone).textContent.trim(), user1Object.get('telephoneNumber'), 'phone is correct in form');
    assert.equal(find(otherId).textContent.trim(), '', 'otherId is blank in form');
    assert.equal(find(username).textContent.trim(), user1Object.get('username'), 'username is correct in form');

    await click(save);

    const userModel = await run(() => this.owner.lookup('service:store').find('user', 5));
    assert.equal(userModel.firstName, user1Object.get('firstName'), 'record created with correct value for firstName');
    assert.equal(userModel.middleName, null, 'record created with correct value for middleName');
    assert.equal(userModel.lastName, user1Object.get('lastName'), 'record created with correct value for lastName');
    assert.equal(userModel.campusId, user1Object.get('campusId'), 'record created with correct value for campusId');
    assert.equal(userModel.otherId, null, 'record created with correct value for otherId');
    assert.equal(userModel.phone, user1Object.get('telephoneNumber'), 'record created with correct value for phone');
    assert.equal(userModel.email, user1Object.get('email'), 'record created with correct value for email');

    const authenticationModel = await userModel.get('authentication');
    assert.equal(authenticationModel.username, user1Object.get('username'), 'record has correct username');
    assert.equal(authenticationModel.password, null, 'record has no password');
    assert.equal(authenticationModel.user.get('id'), '5', 'we are linking to the expected user');
  });
});
<|endoftext|>


<commit_before>/**
 * @author Christian Schulze
 */

(function() {
    'use strict';

    angular
        .module('ActivityLogger')
        .factory('MockDataService',
            function(Activity, Competition, User) {
                var users = [];
                var competitions = [];
                var activities = [];

                var nextCompetitionID = 0;
                var nextActivityID = 0;

                var currentUserID = null;

                function getAllUsers() {
                    return users;
                }

                function addUser(user) {
                    users.push(user);

                    return user.id;
                }

                function getUserByID(id) {
                    for (var i = 0; i < users.length; i++) {
                        if (users[i].id == id) {
                            return users[i];
                        }
                    }

                    return null;
                }

                function setCurrentUserId(id) {
                    currentUserID = id;
                }

                function getCurrentUserId() {
                    return currentUserID;
                }

                function addActivity(activity) {
                    activity.id = nextActivityID;
                    nextActivityID += 1;
                    activities.push(activity);

                    return activity.id;
                }

                function getAllActivities(user_id) {
                    return activities.filter(function(el, i) {
                        return el.userId == user_id;
                    });
                }

                function getActivityByID(id) {
                    for (var i = 0; i < activities.length; i++) {
                        if (activities[i].id == id) {
                            return activities[i];
                        }
                    }

                    return null;
                }

                function removeActivity(id) {
                    return null;
                }

                function addCompetition(competition) {
                    competition.id = nextCompetitionID;
                    nextCompetitionID += 1;
                    competitions.push(competition);

                    return competition.id;
                }

                function getCompetitionByID(id) {
                    for (var i = 0; i < competitions.length; i++) {
                        if (competitions[i].id == id) {
                            return competitions[i];
                        }
                    }

                    return null;
                }

                function getAllCompetitions() {
                    return competitions;
                }

                // mock some data
                addUser(new User('Foobar', 'Foo', 'Bar', 'Male', '34.3.4192', 118, 167));
                addUser(new User('Foobaz', 'Baz', 'Foo', 'Female', '13.3.1992', 64, 165));

                currentUserID = users[0].id;

                var track1 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.578581,
                        longitude: -118.291994,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.606111,
                        longitude: -118.062778,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.433269,
                        longitude: -117.950916,
                        speed: 0
                    },
                    timestamp: 1422290070000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.588056,
                        longitude: -116.943056,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.339722,
                        longitude: -117.467778,
                        speed: 0
                    },
                    timestamp: 1422290120000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.23998,
                        longitude: -116.83171,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];
                var track2 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5851,
                        longitude: 8.6841,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5866,
                        longitude: 8.6815,
                        speed: 0
                    },
                    timestamp: 1422290042000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5874,
                        longitude: 8.6840,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5860,
                        longitude: 8.6861,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];
                var track3 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7967,
                        longitude: 8.7688,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7950,
                        longitude: 8.7689,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7943,
                        longitude: 8.7625,
                        speed: 0
                    },
                    timestamp: 1422290070000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5851,
                        longitude: 8.6841,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];

                addActivity(new Activity(0,
                    "Run",
                    1422290032000,
                    1422290100000, track1, "", 1589.34, users[0].id));

                addActivity(new Activity(0,
                    "Bike",
                    1422290031199,
                    1422290076071,
                    track2, "", 1589.4696498299068, users[0].id));

                var anActivity = addActivity(new Activity(0,
                    "Run",
                    1422290076071,
                    1422290031199, track3, "", 1589.4696498299068, users[1].id));

                var aCompetition = new Competition(0, users[1].id, users[0].id, anActivity, null, 1000);
                addCompetition(aCompetition);

                return {
                    getAllUsers: getAllUsers,
                    addUser: addUser,
                    getUserByID: getUserByID,
                    getCurrentUserId: getCurrentUserId,
                    setCurrentUserId: setCurrentUserId,
                    addActivity: addActivity,
                    getAllActivities: getAllActivities,
                    getActivityByID: getActivityByID,
                    removeActivity: removeActivity,
                    addCompetition: addCompetition,
                    getCompetitionByID: getCompetitionByID,
                    getAllCompetitions: getAllCompetitions
                };
            });
})();<commit_msg>implemented removeActivity();<commit_after>/**
 * @author Christian Schulze
 */

(function() {
    'use strict';

    angular
        .module('ActivityLogger')
        .factory('MockDataService',
            function(Activity, Competition, User) {
                var users = [];
                var competitions = [];
                var activities = [];

                var nextCompetitionID = 0;
                var nextActivityID = 0;

                var currentUserID = null;

                function getAllUsers() {
                    return users;
                }

                function addUser(user) {
                    users.push(user);

                    return user.id;
                }

                function getUserByID(id) {
                    for (var i = 0; i < users.length; i++) {
                        if (users[i].id == id) {
                            return users[i];
                        }
                    }

                    return null;
                }

                function setCurrentUserId(id) {
                    currentUserID = id;
                }

                function getCurrentUserId() {
                    return currentUserID;
                }

                function addActivity(activity) {
                    activity.id = nextActivityID;
                    nextActivityID += 1;
                    activities.push(activity);

                    return activity.id;
                }

                function getAllActivities(user_id) {
                    return activities.filter(function(el, i) {
                        return el.userId == user_id;
                    });
                }

                function getActivityByID(id) {
                    for (var i = 0; i < activities.length; i++) {
                        if (activities[i].id == id) {
                            return activities[i];
                        }
                    }

                    return null;
                }

                function removeActivity(id) {
                    for (var i = 0; i < activities.length; i++) {
                        if (activities[i].id == id) {
                            activities.splice(activity[i], 1);
                        }
                    }
                }

                function addCompetition(competition) {
                    competition.id = nextCompetitionID;
                    nextCompetitionID += 1;
                    competitions.push(competition);

                    return competition.id;
                }

                function getCompetitionByID(id) {
                    for (var i = 0; i < competitions.length; i++) {
                        if (competitions[i].id == id) {
                            return competitions[i];
                        }
                    }

                    return null;
                }

                function getAllCompetitions() {
                    return competitions;
                }

                // mock some data
                addUser(new User('Foobar', 'Foo', 'Bar', 'Male', '34.3.4192', 118, 167));
                addUser(new User('Foobaz', 'Baz', 'Foo', 'Female', '13.3.1992', 64, 165));

                currentUserID = users[0].id;

                var track1 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.578581,
                        longitude: -118.291994,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.606111,
                        longitude: -118.062778,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.433269,
                        longitude: -117.950916,
                        speed: 0
                    },
                    timestamp: 1422290070000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.588056,
                        longitude: -116.943056,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.339722,
                        longitude: -117.467778,
                        speed: 0
                    },
                    timestamp: 1422290120000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 36.23998,
                        longitude: -116.83171,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];
                var track2 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5851,
                        longitude: 8.6841,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5866,
                        longitude: 8.6815,
                        speed: 0
                    },
                    timestamp: 1422290042000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5874,
                        longitude: 8.6840,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5860,
                        longitude: 8.6861,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];
                var track3 = [{
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7967,
                        longitude: 8.7688,
                        speed: 0
                    },
                    timestamp: 1422290032000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7950,
                        longitude: 8.7689,
                        speed: 0
                    },
                    timestamp: 1422290052000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.7943,
                        longitude: 8.7625,
                        speed: 0
                    },
                    timestamp: 1422290070000
                }, {
                    coords: {
                        accuracy: 1,
                        altitude: -0.134625,
                        altitudeAccuracy: null,
                        heading: 0,
                        latitude: 50.5851,
                        longitude: 8.6841,
                        speed: 0
                    },
                    timestamp: 1422290100000
                }];

                addActivity(new Activity(0,
                    "Run",
                    1422290032000,
                    1422290100000, track1, "", 1589.34, users[0].id));

                addActivity(new Activity(0,
                    "Bike",
                    1422290031199,
                    1422290076071,
                    track2, "", 1589.4696498299068, users[0].id));

                var anActivity = addActivity(new Activity(0,
                    "Run",
                    1422290076071,
                    1422290031199, track3, "", 1589.4696498299068, users[1].id));

                var aCompetition = new Competition(0, users[1].id, users[0].id, anActivity, null, 1000);
                addCompetition(aCompetition);

                return {
                    getAllUsers: getAllUsers,
                    addUser: addUser,
                    getUserByID: getUserByID,
                    getCurrentUserId: getCurrentUserId,
                    setCurrentUserId: setCurrentUserId,
                    addActivity: addActivity,
                    getAllActivities: getAllActivities,
                    getActivityByID: getActivityByID,
                    removeActivity: removeActivity,
                    addCompetition: addCompetition,
                    getCompetitionByID: getCompetitionByID,
                    getAllCompetitions: getAllCompetitions
                };
            });
})();<|endoftext|>


<commit_before>'use strict';

define([
	'chai', 'underscore', './sandboxManager', 'esencia/view'
], function(chai, _, SandboxManager, View) {
	var expect = chai.expect;

	var sandboxManager = new SandboxManager();

	describe('View', function() {
		describe('.constructor()', function() {
			it('should set default fields', function() {
				var view = new View();

				expect(view.noel).to.be.equal(true);
				expect(view.el).to.be.an('object');
				expect(view.el.tagName).to.be.equal('DIV');
				expect(view.$el[0]).to.be.equal(view.el);

				_(['data', 'options', 'views', '_viewsEventsHash', 'templateHelpers']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should not set noel if el selector is passed', function() {
				var el = sandboxManager.getSelector();
				var view = new View({el: el});

				expect(view.noel).to.not.be.ok();
				expect(view.el).to.be.equal(sandboxManager.get(el).get(0));

				sandboxManager.remove(el);
			});

			it('should set additional fields from options', function() {
				var view = new View({
					models: {},
					collections: {},
					views: {},
					viewsEvents: {},
					urlParams: {}
				});

				_(['models', 'collections', 'views', 'viewsEvents', 'urlParams']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should set additional fields from prototype', function() {
				var view = new (View.extend({
					models: {},
					collections: {},
					views: {},
					viewsEvents: {},
					urlParams: {}
				}))();

				_(['models', 'collections', 'views', 'viewsEvents', 'urlParams']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should normalize nested views object', function() {
				var view = new View({
					views: {
						'#non-array': new View(),
						'#empty': []
					}
				});

				var viewsData = {
					'#non-array': 1,
					'#empty': 0
				};

				_(viewsData).each(function(count, selector) {
					expect(view.views).to.have.property(selector);
					expect(view.views[selector]).to.be.an('array');
					expect(view.views[selector]).to.have.length(count);
				});
			});

			it('should fill _viewsEventsHash from viewsEvents', function() {
				var view = new (View.extend({
					viewsEvents: {
						'event1 #selector1': function() {},
						'event2 #selector1': 'method',
						'event3 #selector2, #selector3': function() {},
						'event4 #selector4': 'wrongMethod'
					},
					method: function() {}
				}))();

				expect(view._viewsEventsHash).to.be.an('object');

				var viewsEventsData = {
					'#selector1': ['event1', 'event2'],
					'#selector2': ['event3'],
					'#selector3': ['event3']
				};

				_(viewsEventsData).each(function(eventNames, selector) {
					expect(view._viewsEventsHash).to.have.property(selector);
					expect(view._viewsEventsHash[selector]).to.be.an('array');
					expect(view._viewsEventsHash[selector]).to.have.length(eventNames.length);

					_(eventNames).each(function(eventName, index) {
						var eventItem = view._viewsEventsHash[selector][index];
						expect(eventItem).to.be.an('object');
						expect(eventItem.eventName).to.be.equal(eventName);
						expect(eventItem.handler).to.be.a('function');
					});
				});

				expect(view._viewsEventsHash).to.not.have.property('#selector4');
			});
		});

		describe('._updateViews() + aliases', function() {
			it('should prepend view with method .prependView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();

				view.prependView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should prepend views array with method .prependViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();

				view.prependViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(4);
				expect(view.views['#selector'][0]).to.be.equal(nestedView1);
				expect(view.views['#selector'][1]).to.be.equal(nestedView2);
			});

			it('should append view with method .appendView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();

				view.appendView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][2]).to.be.equal(nestedView);
			});

			it('should append views array with method .appendViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();

				view.appendView([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(4);
				expect(view.views['#selector'][2]).to.be.equal(nestedView1);
				expect(view.views['#selector'][3]).to.be.equal(nestedView2);
			});

			it('should insert view to specific position with method .insertView()',
				function() {
					var view = new View({
						views: {
							'#selector': [new View(), new View()]
						}
					});

					var nestedView = new View();

					view.insertView(nestedView, '#selector', 1);

					expect(view.views['#selector']).to.be.an('array');
					expect(view.views['#selector']).to.have.length(3);
					expect(view.views['#selector'][1]).to.be.equal(nestedView);
				}
			);

			it('should insert views array to specific position with method ' +
				'.insertViews()', function() {
					var view = new View({
						views: {
							'#selector': [new View(), new View()]
						}
					});

					var nestedView1 = new View();
					var nestedView2 = new View();

					view.insertViews([nestedView1, nestedView2], '#selector', 1);

					expect(view.views['#selector']).to.be.an('array');
					expect(view.views['#selector']).to.have.length(4);
					expect(view.views['#selector'][1]).to.be.equal(nestedView1);
					expect(view.views['#selector'][2]).to.be.equal(nestedView2);
				}
			);

			it('should set view with method .setView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();
				view.setView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should set views array with method .setViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();
				view.setViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(2);
				expect(view.views['#selector'][0]).to.be.equal(nestedView1);
				expect(view.views['#selector'][1]).to.be.equal(nestedView2);
			});

			it('should replace views with method .replaceView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();
				view.replaceView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should replace view by index with method .replaceView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View(), new View()]
					}
				});

				var nestedView = new View();
				view.replaceView(nestedView, '#selector', 1);

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][1]).to.be.equal(nestedView);
			});

			it('should remove view by index with method .removeView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				view.removeView('#selector', 1);

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
			});

			it('should remove views array with method .removeViews()', function() {
				var nestedView1 = new View();
				var nestedView2 = new View();

				var view = new View({
					views: {
						'#selector': [nestedView1, new View(), nestedView2]
					}
				});

				view.removeViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
			});
		});
	});
});
<commit_msg>fix tests<commit_after>'use strict';

define([
	'chai', 'underscore', './sandboxManager', 'esencia/view'
], function(chai, _, SandboxManager, View) {
	var expect = chai.expect;

	var sandboxManager = new SandboxManager();

	describe('View', function() {
		describe('.constructor()', function() {
			it('should set default fields', function() {
				var view = new View();

				expect(view.noel).to.be.equal(true);

				_(['data', 'options', 'views', '_viewsEventsHash', 'templateHelpers']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should not set noel if el selector is passed', function() {
				var el = sandboxManager.getSelector();
				var view = new View({el: el});

				expect(view.noel).to.equal(undefined);
				expect(view.el).to.be.equal(sandboxManager.get(el).get(0));

				sandboxManager.remove(el);
			});

			it('should set additional fields from options', function() {
				var view = new View({
					models: {},
					collections: {},
					views: {},
					viewsEvents: {},
					urlParams: {}
				});

				_(['models', 'collections', 'views', 'viewsEvents', 'urlParams']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should set additional fields from prototype', function() {
				var view = new (View.extend({
					models: {},
					collections: {},
					views: {},
					viewsEvents: {},
					urlParams: {}
				}))();

				_(['models', 'collections', 'views', 'viewsEvents', 'urlParams']).each(
					function(key) {
						expect(view[key]).to.be.eql({});
					}
				);
			});

			it('should normalize nested views object', function() {
				var view = new View({
					views: {
						'#non-array': new View(),
						'#empty': []
					}
				});

				var viewsData = {
					'#non-array': 1,
					'#empty': 0
				};

				_(viewsData).each(function(count, selector) {
					expect(view.views).to.have.property(selector);
					expect(view.views[selector]).to.be.an('array');
					expect(view.views[selector]).to.have.length(count);
				});
			});

			it('should fill _viewsEventsHash from viewsEvents', function() {
				var view = new (View.extend({
					viewsEvents: {
						'event1 #selector1': function() {},
						'event2 #selector1': 'method',
						'event3 #selector2, #selector3': function() {},
						'event4 #selector4': 'wrongMethod'
					},
					method: function() {}
				}))();

				expect(view._viewsEventsHash).to.be.an('object');

				var viewsEventsData = {
					'#selector1': ['event1', 'event2'],
					'#selector2': ['event3'],
					'#selector3': ['event3']
				};

				_(viewsEventsData).each(function(eventNames, selector) {
					expect(view._viewsEventsHash).to.have.property(selector);
					expect(view._viewsEventsHash[selector]).to.be.an('array');
					expect(view._viewsEventsHash[selector]).to.have.length(eventNames.length);

					_(eventNames).each(function(eventName, index) {
						var eventItem = view._viewsEventsHash[selector][index];
						expect(eventItem).to.be.an('object');
						expect(eventItem.eventName).to.be.equal(eventName);
						expect(eventItem.handler).to.be.a('function');
					});
				});

				expect(view._viewsEventsHash).to.not.have.property('#selector4');
			});
		});

		describe('._updateViews() + aliases', function() {
			it('should prepend view with method .prependView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();

				view.prependView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should prepend views array with method .prependViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();

				view.prependViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(4);
				expect(view.views['#selector'][0]).to.be.equal(nestedView1);
				expect(view.views['#selector'][1]).to.be.equal(nestedView2);
			});

			it('should append view with method .appendView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();

				view.appendView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][2]).to.be.equal(nestedView);
			});

			it('should append views array with method .appendViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();

				view.appendView([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(4);
				expect(view.views['#selector'][2]).to.be.equal(nestedView1);
				expect(view.views['#selector'][3]).to.be.equal(nestedView2);
			});

			it('should insert view to specific position with method .insertView()',
				function() {
					var view = new View({
						views: {
							'#selector': [new View(), new View()]
						}
					});

					var nestedView = new View();

					view.insertView(nestedView, '#selector', 1);

					expect(view.views['#selector']).to.be.an('array');
					expect(view.views['#selector']).to.have.length(3);
					expect(view.views['#selector'][1]).to.be.equal(nestedView);
				}
			);

			it('should insert views array to specific position with method ' +
				'.insertViews()', function() {
					var view = new View({
						views: {
							'#selector': [new View(), new View()]
						}
					});

					var nestedView1 = new View();
					var nestedView2 = new View();

					view.insertViews([nestedView1, nestedView2], '#selector', 1);

					expect(view.views['#selector']).to.be.an('array');
					expect(view.views['#selector']).to.have.length(4);
					expect(view.views['#selector'][1]).to.be.equal(nestedView1);
					expect(view.views['#selector'][2]).to.be.equal(nestedView2);
				}
			);

			it('should set view with method .setView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();
				view.setView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should set views array with method .setViews()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView1 = new View();
				var nestedView2 = new View();
				view.setViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(2);
				expect(view.views['#selector'][0]).to.be.equal(nestedView1);
				expect(view.views['#selector'][1]).to.be.equal(nestedView2);
			});

			it('should replace views with method .replaceView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				var nestedView = new View();
				view.replaceView(nestedView, '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
				expect(view.views['#selector'][0]).to.be.equal(nestedView);
			});

			it('should replace view by index with method .replaceView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View(), new View()]
					}
				});

				var nestedView = new View();
				view.replaceView(nestedView, '#selector', 1);

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(3);
				expect(view.views['#selector'][1]).to.be.equal(nestedView);
			});

			it('should remove view by index with method .removeView()', function() {
				var view = new View({
					views: {
						'#selector': [new View(), new View()]
					}
				});

				view.removeView('#selector', 1);

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
			});

			it('should remove views array with method .removeViews()', function() {
				var nestedView1 = new View();
				var nestedView2 = new View();

				var view = new View({
					views: {
						'#selector': [nestedView1, new View(), nestedView2]
					}
				});

				view.removeViews([nestedView1, nestedView2], '#selector');

				expect(view.views['#selector']).to.be.an('array');
				expect(view.views['#selector']).to.have.length(1);
			});
		});
	});
});
<|endoftext|>


<commit_before>export default [
  '._*',
  '.hg',
  '.git',
  '.svn',
  '.gitignore',
  '.npmrc',
  '.*.swp',
  '.DS_Store',
  '.wafpickle-*',
  '.lock-wscript',
  'npm-debug.log',
  'config.gypi',
  'node_modules',
  'CVS',
  'README',
  'README.*',
  'CHANGELOG',
  'History.md',
  'LICENSE',
  'Readme',
  'Readme.*',
  'test',
  'tests'
];
<commit_msg>update ignores list<commit_after>export default [
  '._*',
  '.hg',
  '.git',
  '.svn',
  '.next',
  '.gitignore',
  '.npmrc',
  '.*.swp',
  '.DS_Store',
  '.wafpickle-*',
  '.lock-wscript',
  'npm-debug.log',
  'config.gypi',
  'node_modules',
  'CVS',
  'README',
  'README.*',
  'CHANGELOG',
  'History.md',
  'LICENSE',
  'Readme',
  'Readme.*',
  'test',
  'tests'
];
<|endoftext|>