{"id":6430,"date":"2014-04-18T05:21:56","date_gmt":"2014-04-18T05:21:56","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/04\/18\/jasmine-testing-fancybox-in-backbone-spied-methods-incorrectly-passing-through-collection-of-common-programming-errors\/"},"modified":"2014-04-18T05:21:56","modified_gmt":"2014-04-18T05:21:56","slug":"jasmine-testing-fancybox-in-backbone-spied-methods-incorrectly-passing-through-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/04\/18\/jasmine-testing-fancybox-in-backbone-spied-methods-incorrectly-passing-through-collection-of-common-programming-errors\/","title":{"rendered":"Jasmine Testing Fancybox in Backbone &#8211; Spied Methods incorrectly passing through-Collection of common programming errors"},"content":{"rendered":"<p>I have a modal login view that I&#8217;m testing with Jasmine. I have a nasty problem testing that the login button redirects. I&#8217;ve put the redirect in a method so that I can mock it and test the call but when I trigger the click event on the sign in button the spy seems to be ignored.<\/p>\n<p>Here&#8217;s the view I&#8217;m testing&#8230;<\/p>\n<pre><code>define(['ministry', 'models\/m-auth', 'helpers\/cookie-manager', 'text!templates\/modals\/login.html', 'jquery.custom'],\nfunction (Ministry, Authentication, CookieManager, TemplateSource) {\n    var loginView = Ministry.SimpleView.extend({\n\n        name: 'Login',\n\n        el: \"#popupLoginWrapper\",\n\n        template: Handlebars.compile(TemplateSource),\n\n        events: {\n            'submit #loginForm': 'signIn'\n        },\n\n        redirectToOrigin: function () {\n            \/\/ TODO: Change location to member home when implemented\n            location.href = '\/#\/jqm';\n        },\n\n        signIn: function (e) {\n            var that = this;\n\n            e.preventDefault();\n\n            \/\/ As we have no input yet log in manually using the auth model...\n            var authData = new Authentication.Request({\n                requestSource: $('#requestSource').text(),\n                apiKey: $('#apiKey').text(),\n                username: '*****',\n                password: '*****'\n            });\n\n            \/\/ This saves the login details, generating a session if necessary, then creates a cookie that lasts for 1 hour\n            authData.save(authData.attributes, {                    \n                success: function () {\n                    if (authData.generatedHash !== undefined &amp;&amp; authData.generatedHash !== null &amp;&amp; authData.generatedHash !== '')\n                        CookieManager.CreateSession(authData.generatedHash);\n                        that.redirectToOrigin();\n                }\n            });\n        },\n    });\n\n    return loginView;\n});\n<\/code><\/pre>\n<p>(It currently logs in with a hard coded account &#8211; wiring up the actual controls is the next job). And here&#8217;s the test in question (I&#8217;ve combined all the before and afters into the test for simplicity here)&#8230;<\/p>\n<pre><code>        var buildAndRenderView = function (viewObject) {\n            viewObject.render();\n            $('#jasmineSpecTestArea').append(viewObject.el);\n            return viewObject;\n        };\n\n        it(\"signs in when the 'Sign In' button is clicked\", function () {\n            spyOn(objUt, 'redirectToOrigin').andCallFake(Helper.DoNothing);\n            spyOn(Backbone.Model.prototype, 'save').andCallFake(function (attributes, params) {\n                params.success();\n            });\n\n            $('body').append('');\n            $('#jasmineSpecTestArea').append('');\n            objUt = new View();\n            buildAndRenderView(objUt);\n\n            objUt.$('#loginForm button').click();\n\n            expect(objUt.redirectToOrigin).toHaveBeenCalled();\n\n            $('#jasmineSpecTestArea').remove();\n        });\n<\/code><\/pre>\n<p>Some brief justification: I do the vast majority of my views as independent components that I then render in a custom view variant called a Region (modeled on Marionette) &#8211; I generally find this to be a nice tidy practice that helps me keep track of what sits where in the app separately from what is held in a given &#8216;space&#8217;. This strategy doesn&#8217;t seem to work with fancybox modals, such as this, so the render takes place in a hidden existing DOM element and is then moved into the region, hence the need for the code to append &#8216;popupLoginWrapper&#8217; into the test area.<\/p>\n<p>The same test above will also fail if I call the sign in method directly with empty event arguments. Jasmine gives me the following error &#8216;Error: Expected a spy, but got Function.&#8217; (Which makes sense, as it&#8217;s calling the actual implementation of redirectToOrigin rather than the spy.<\/p>\n<p>I have similar tests which pass, and the issue seems to be around the triggering of params.success(), but this is necessary to the test.<\/p>\n<p>ADDITIONAL: After disabling the test, I found this issue affecting most of the tests for this modal. By stepping through, I can see that the spy is applied and the spy code is executed in some cases, but then the real success call seems to then be triggered afterwards.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I have a modal login view that I&#8217;m testing with Jasmine. I have a nasty problem testing that the login button redirects. I&#8217;ve put the redirect in a method so that I can mock it and test the call but when I trigger the click event on the sign in button the spy seems to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-6430","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=6430"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6430\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=6430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=6430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=6430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}