working on it ...

Filters

Explore Public Snippets

Sort by

Found 5 snippets matching: sinonjs

    public by JKCPR modified Apr 25, 2018  786  0  5  1

    unit testing - mocking server responses with sinonjs

    {
        setUp: function () {
            this.server = sinon.fakeServer.create();
        },
    
        tearDown: function () {
            this.server.restore();
        },
    
        "test should fetch comments from server" : function () {
            this.server.respondWith("GET", "/some/article/comments.json",
                                    [200, { "Content-Type": "application/json" },
                                     '[{ "id": 12, "comment": "Hey there" }]']);
    
            var callback = sinon.spy();
            myLib.getCommentsFor("/some/article", callback);
            this.server.respond();
    
            sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));
        }
    }		

    external by ldong modified Jul 25, 2014  114  3  2  0

    javascript testing library - SinonJS

    javascript testing library - SinonJS: javascript_sinon_js.md
    # JavaScript
    
    ## Sinon
    
    What is Sinon? It is a unit test library for JavaScript.
    
    It has 5 parts:
    
    1. [Spy](#spy): The Test Spy is designed to act as an observation point
     by recording the method calls made to it by the SUT as it is exercised.
    
    2. [Stub](#stub): The Test Stub replaces a real object with a test-specific
     object that feeds the desired indirect inputs into the system under test.
     Stubs do not proxy original methods.
     Stubs have an API for controlling behavior.
    
    3. [Mock](#mock): The mock replaces an object the system under test (SUT)
     depends on with a test-specific object that verifies it is being used
     correctly by the SUT.
     State expectations up-front.
     No need for assertions.
     Mocks are spies and stubs.
    
    4. [Fake Timers](#fake-timers).
    
    5. [Fake Servers](#fake-servers):
        Declare responses upfront
        "Unknown" requests get a 404
        Process async requests with server.respond()
    
    
    ## Spy
    
    “A test spy is a function that records arguments, return value, the value of
     this and exception thrown (if any) for all its calls. A test spy can be an
     anonymous function or it can wrap an existing function.”
    
    Features: `called`, `callCount`, `calledWith`, `threw`, `returned`.
    
    1. Create a spy function
        ```javascript
        var callback = sinon.spy();
    
        callback(); // Invoke the spy callback function
    
        callback.called;
        callback.callCount;
        callback.calledWith(arg1);
        callback.threw();
        callback.returned(obj);
        callback.calledBefore(spy);
        callback.calledAfter(spy);
        ```
    
    2. Turn an existing function into a spy function
    
        ```javascript
        sinon.spy($, "ajax");
    
        $.ajax({ / ... / }); // Call spy version of jQuery.ajax
    
        var call = $.ajax.getCall(0);
    
        call.args;
        call.exception;
        call.returnValue;
    
        $.ajax.restore();
    
        ```
    
    
    ## Stub
    
    “Test stubs are functions (spies) with pre-programmed behavior.
     They support the full test spy API in addition to methods which
     can be used to alter the stub's behavior.”
    
    
    Example
    
    ```javascript
    var stub = sinon.stub(),
        opts = { call: function (msg) { console.log(msg); } };
    
    // We can control how the sinon.stub() will behave based on how it’s called!
    stub.withArgs("Hello").returns("World");
    stub.withArgs("Wuz").returns("Zup?");
    stub.withArgs("Kapow").throws();
    stub.withArgs(opts).yieldsTo("call", ["Howdy"]);
    
    stub("Hello"); // "World"
    stub(options); // "Howdy"
    
    
    // notes, all above stub.withArgs(opts) can be replaced
    // with stub.yieldsTo(property, [arg1, arg2, ...])
    ```
    
    Another example [mockServer.coffee](http://git.io/voRZ6g)
    uses `ajax`, `yieldsTo`
    
    
    ## Mock
    
    “Mocks (and mock expectations) are fake methods (like spies)
     with pre-programmed behavior (like stubs) as well as pre-programmed
     expectations. A mock will fail your test if it is not used as expected.”
    
    i.e.
    
    ```javascript
    var opts = { call: function (msg) { console.log(msg); } },
        mock = sinon.mock(opts);
    
    // You state your success criteria upfront
    mock.expects("call").once().withExactArgs("Hello World");
    /* ... twice, atMost, never, exactly, on, etc ... */
    
    opts.call("Hello World");
    
    mock.verify();
    
    mock.restore();
    ```
    
    ## Fake Timers
    
    "Fake timers is a synchronous implementation of setTimeout and friends that
     Sinon.JS can overwrite the global functions with to allow you to more easily
     test code using them."
    
    Example:
    
    ```javascript
    
    var clock = sinon.useFakeTimers();
    
    var hidden =
        $("<div hidden="">Peekaboo</div>")
            .appendTo(document.body).fadeIn("slow");
    
    clock.tick(650); // slow = 600ms
    hidden.css("opacity") === 1; // true
    
    clock.restore();
    ```
    
    `clock.tick(650)` will set our time 650 ms ahead, thus
     `hidden.css("opacity")` will be true.
    
    
    ## Fake Servers
    
    “High-level API to manipulate FakeXMLHttpRequest instances.”
    
    ```javascript
    var server = sinon.fakeServer.create();
    
    server.respondWith("GET", "/twitter/api/user.json", [
        200,
        {"Content-Type": "application/json"},
        '[{"id": 0, "tweet": "Hello World"}]'
    ]);
    
    $.get("/twitter/api/user.json", function (data) {
        console.log(data); // [{"id":0,"tweet":"Hello World"}]
    });
    server.respond();
    
    server.restore();
    ```
    
    ### Note
    
    So, what is the difference between using Fake Servers or just stub on the ajax
     call? To me, you could use either. Use Fake Servers if you want to test it on
     the system level rather than function levels. There you have it, how to use
     Sinon.JS.
    
    
    # Reference
    
    [Sinon official docs]
    (http://sinonjs.org/docs/)
    
    [Unit Test like a Secret Agent with Sinon.js]
    (http://www.elijahmanor.com/unit-test-like-a-secret-agent-with-sinon-js/)
    
    [Sinon - Simplifying JavaScript testing]
    (http://cjohansen.no/talks/2011/xp-meetup/#1)
    
    [JavaScript Test Spies, Stubs and Mocks]
    (http://cjohansen.no/en/javascript/javascript_test_spies_stubs_and_mocks)
    
    [Design Goals]
    (http://cjohansen.no/talks/2011/xp-meetup/#6)
    
    [一款颇具特色的前端单元测试工具——Sinon.js]
    (http://www.36ria.com/6194)
    
    
    

    external by Jorge Luis Rivera Bocanegra modified Nov 19, 2015  80  0  1  0

    Stubbing XHRs in QUnit with SinonJS Fake Server

    Stubbing XHRs in QUnit with SinonJS Fake Server: example.js
    QUnit.module("my-module",
    {
      setup: function () {
        // Configure Sinon's FakeServer instance.  `autoRespond` ensures that any incoming requests
        // will automatically be replied to, otherwise you *must* invoke `this.server.respond` to
        // start processing.
        this.server = sinon.fakeServer.create();
        this.server.autoRespond = true;
    
        // Tells the FakeServer's XHR request factory that we don't want to respond to every
        // request (ie: some requests should be allowed to pass through unmodified)
        this.server.xhr.useFilters = true;
    
        var requestUrisOrRegexes = this.requestUrisOrRegexes = [];
    
        // Add an XHR filter which looks at for any matching URIs which were added using `this.stubXhrRequest`.
        this.server.xhr.addFilter(function (method, uri) {
          var matched = false;
    
          // Deal with the fact `this.stubRequest` accepts both a string and a regex.
          function isMatch (matcher) {
              return (typeof matcher === "string") ? matcher === uri : matcher.exec(uri) !== null;
          }
    
          // Check all matchers to see if one matches the incoming URI.
          for (var i = 0; i < requestUrisOrRegexes.length; i++) {
              matched = isMatch(requestUrisOrRegexes[i]);
              if (matched) break;
          }
    
          // Sinon FakeXHR filters need to return `false` if the request should be stubbed and
          // `true` if it should be allowed to pass through.
          return !matched;
        });
      },
    
      teardown: function () {
          this.server.restore();
      },
    
      // Return a pre-canned response object for a given URI.
      stubXhrRequest: function (uriOrRegex, responseObject) {
        // Store the uriOrRegex value so the FakeXHR filter can indicate this request
        // should be faked.
        this.requestUrisOrRegexes.push(uriOrRegex);
    
        var responseCode = 200;
        var responseHeaders = { "Content-Type": "application/json" };
        var responseBody = JSON.stringify(responseObject);
    
        this.server.respondWith(uriOrRegex,
            [ responseCode, responseHeaders, responseBody ]
        );
      }
    });
    
    QUnit.asyncTest("When a request to `/foo/bar` is made, the `id` should be extracted from the response", function (assert) {
      var expectedId = 303;
    
      // First arg is a regex or a string which will be used to determine if the supplied response
      // should be served.  Second argument is an Object which will be marshalled into JSON by the
      // `stubXhrRequest` method.
      this.stubXhrRequest(/^\/foo\/bar/, { id: expectedId, body: "hello world!" });
    
      // Kick off our example integration test.
      myModule.getId("/foo/bar", function (id) {
        // Example assertion assuming `myModule.getId` will invoke this callback when the XHR compeltes.
        assert.equal(id, expectedId, "id was extracted from the response object");
    
        // Complete this async test.
        QUnit.start();
      });
    });
    
    

    external by NorthDecoder modified Apr 12, 2015  80  0  1  0

    HTML5 template test with qunit and sinonjs

    HTML5 template test with qunit and sinonjs: HTML5_test_with_qunit.html
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS tests</title>
      <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.17.1.css">
    </head>
    
    <body>
      <div id="qunit"></div>
      <div id="qunit-fixture">
        <input type='submit' id='context_submit' value='context'>
        <script>$('#context_submit').click(function() {});</script>
      </div>
      <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="details.js"></script>
      <script src="http://code.jquery.com/qunit/qunit-1.17.1.js"></script>
    
      <script src="http://sinonjs.org/releases/sinon-1.12.2.js"></script>
      <script src="tests.js"></script>
    
    </body>
    </html>
    
    
    

    external by fatso83 modified Jul 28, 2016  23  0  1  0

    Test script for sinonjs/sinon#1113. Place it one level above the project and run `sh ../test-script.sh` to test it

    Test script for sinonjs/sinon#1113. Place it one level above the project and run `sh ../test-script.sh` to test it: test-script.sh
    #!/bin/bash
    # test script built for use with `git bisect` to find a regression
    # usage: git bisect start v1.16.1 v1.15.4  && git bisect run ../test-script.sh
    #
    # Warning: You need a Node version <= 0.12.5
    # Since this script checks out former versions of Sinon, that had build scripts
    # that relied on the directory layout of NPM versions < 3, it is wise to
    # use `nvm` or `n` to set the current Node version to 0.12.5 or equivalent
    
    # To support running this script when it is placed outside of the project
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    echo SCRIPT_DIR=$SCRIPT_DIR
    echo PWD=$PWD
    
    # delete node_modules to avoid errors on `npm install` - does not delete .bin
    /bin/rm -r node_modules/*
    
    npm install && ./build || exit 1
    
    # install the karma browser runner
    if [[ -e $SCRIPT_DIR/backup-karma-dir ]]; then
        echo "Reusing previous Karma download"
        cp -r $SCRIPT_DIR/backup-karma-dir/* node_modules/
    else
        #reinstall
        npm install karma mocha chai karma-chrome-launcher karma-mocha karma-chai
    
        # save for later for speed up
        mkdir "$SCRIPT_DIR/backup-karma-dir"
        pushd node_modules
        cp -r karma* phantomjs mocha chai "$SCRIPT_DIR/backup-karma-dir/"
        popd
    fi
    
    # make a karma config
    cat > $SCRIPT_DIR/karma.conf << EOF
    module.exports = function (config) {
    	config.set({
    		basePath : '.',
    
    		// frameworks to use
    		frameworks : ['mocha', 'chai'],
    
            reporters : ['progress'],
    
    		// list of files / patterns to load in the browser
    		files : [
                'sinon/pkg/sinon.js',
    			'regression.test.js'
    		],
    
    		browsers : ['Chrome' ],
            singleRun : true
    	});
    };
    EOF
    
    cat > $SCRIPT_DIR/regression.test.js << EOF
    describe('#1113', function() {
    
        it('should pass', function() {
            var actual = ['foo'];
            actual.hasCustomProperty = true;
    
            var match = sinon.match(['foo']);
            assert.equal(match.test(actual),true); // => false
        });
    });
    EOF
    
    
    # run the tests
    ./node_modules/.bin/karma start  $SCRIPT_DIR/karma.conf
    
    
    

    List Complete ( 5 snippets total )

    • Public Snippets
    • Channels Snippets