working on it ...


Explore Public Snippets

Sort by

Found 5 snippets matching: sinonjs

    public by JKCPR  822  0  5  1

    unit testing - mocking server responses with sinonjs

        setUp: function () {
            this.server = sinon.fakeServer.create();
        tearDown: function () {
        "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);
            sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));

    external by ldong  114  3  2  0

    javascript testing library - SinonJS

    javascript testing library - SinonJS:
    # 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
        var callback = sinon.spy();
        callback(); // Invoke the spy callback function
    2. Turn an existing function into a spy function
        sinon.spy($, "ajax");
        $.ajax({ / ... / }); // Call spy version of jQuery.ajax
        var call = $.ajax.getCall(0);
    ## 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.”
    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(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 [](
    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.”
    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 ... */"Hello World");
    ## 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."
    var clock = sinon.useFakeTimers();
    var hidden =
        $("<div hidden="">Peekaboo</div>")
    clock.tick(650); // slow = 600ms
    hidden.css("opacity") === 1; // true
    `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.”
    var server = sinon.fakeServer.create();
    server.respondWith("GET", "/twitter/api/user.json", [
        {"Content-Type": "application/json"},
        '[{"id": 0, "tweet": "Hello World"}]'
    $.get("/twitter/api/user.json", function (data) {
        console.log(data); // [{"id":0,"tweet":"Hello World"}]
    ### 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
    # Reference
    [Sinon official docs]
    [Unit Test like a Secret Agent with Sinon.js]
    [Sinon - Simplifying JavaScript testing]
    [JavaScript Test Spies, Stubs and Mocks]
    [Design Goals]

    external by Jorge Luis Rivera Bocanegra  80  0  1  0

    Stubbing XHRs in QUnit with SinonJS Fake Server

    Stubbing XHRs in QUnit with SinonJS Fake Server: example.js
      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 () {
      // 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.
        var responseCode = 200;
        var responseHeaders = { "Content-Type": "application/json" };
        var responseBody = JSON.stringify(responseObject);
            [ 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.

    external by NorthDecoder  79  0  1  0

    HTML5 template test with qunit and sinonjs

    HTML5 template test with qunit and sinonjs: HTML5_test_with_qunit.html
    <!DOCTYPE html>
      <meta charset="utf-8">
      <title>JS tests</title>
      <link rel="stylesheet" href="">
      <div id="qunit"></div>
      <div id="qunit-fixture">
        <input type='submit' id='context_submit' value='context'>
        <script>$('#context_submit').click(function() {});</script>
      <script src=""></script>
      <script src="details.js"></script>
      <script src=""></script>
      <script src=""></script>
      <script src="tests.js"></script>

    external by fatso83  23  0  1  0

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

    Test script for sinonjs/sinon#1113. Place it one level above the project and run `sh ../` to test it:
    # 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 ../
    # 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 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/
        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/"
    # make a karma config
    cat > $SCRIPT_DIR/karma.conf << EOF
    module.exports = function (config) {
    		basePath : '.',
    		// frameworks to use
    		frameworks : ['mocha', 'chai'],
            reporters : ['progress'],
    		// list of files / patterns to load in the browser
    		files : [
    		browsers : ['Chrome' ],
            singleRun : true
    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
    # run the tests
    ./node_modules/.bin/karma start  $SCRIPT_DIR/karma.conf

    List Complete ( 5 snippets total )

    • Public Snippets
    • Channels Snippets