Stub out a jQuery selector call?

后端 未结 3 1852
别跟我提以往
别跟我提以往 2020-12-15 04:36

I\'m trying to get better at unit testing my JavaScript. I have the following code:

var categoryVal = $(\'#category\').val();
if (categoryVal === \'\') { 
           


        
3条回答
  •  [愿得一人]
    2020-12-15 05:22

    Here is a pretty good guide to testing your views if you are using Backbone.js and Jasmin. Scroll down to the View section.

    http://tinnedfruit.com/2011/04/26/testing-backbone-apps-with-jasmine-sinon-3.html

    True, the stubs operate on objects. I guess the point of creating a view stub like so.

    this.todoViewStub = sinon.stub(window, "TodoView")
            .returns(this.todoView);
    

    Is just to be able to later render the view.

    this.view.render();
    

    In other words, append the '#category' div to the DOM of the testrunner, so that $ can act upon it. If your '#category' div is not in this.view, then you probably can just create a test.html page in which you run your isolated test. This is a common pattern in the Javascript MVC framework that I'm more used to that Backbone.

    Here is a simple JMVC application structure example:

    /todo
       /models
          todo.js
       /list
          /views
             init.tmpl
             listItem.tmpl
          list.css           
          list.js        (Controller)
          unitTest.js    (Tests for your list.)
          list_test.html (A html for your unit tests to run on.)
    

    Having this setup you could just include the "#category" div in your list_test.html if you don't already happen to have it inside one of the views.

提交回复
热议问题