Giter VIP home page Giter VIP logo

sinon's People

Contributors

bryandonovan avatar cincodenada avatar cjohansen avatar dependabot-preview[bot] avatar dependabot[bot] avatar domenic avatar dominykas avatar ebi avatar fatso83 avatar fearphage avatar felixge avatar flarna avatar havardh avatar ig-pj avatar jonnyreeves avatar jsok avatar kpdecker avatar lfac-pt avatar lucasfcosta avatar mantoni avatar marvinthepa avatar mgred avatar mhmoudgmal avatar mrbigdog2u avatar mroderick avatar neonstalwart avatar papandreou avatar pimterry avatar tf avatar timruffles avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sinon's Issues

Unable to run in Rhino w/Env.js

Hi, I am using Rhino+Env.js to run my unit tests as part of an ant build step. This has been working great for me, until I included some tests with Sinon.js. Once I did that, I started getting errors which prevent the tests from running correctly. The error output is included below for reference.

I am using Sinon 1.0.0, Rhino 1.7 release 2 2009 03 22, and env.rhino.1.2.js.

 [java] The args attribute is deprecated. Please use nested arg elements.
 [java] [  Envjs/1.6 (Rhino; U; Mac OS X x86_64 10.6.6; en-US; rv:1.7.0.rc2) Resig/20070309 PilotFish/1.2.13  ]
 [java] Loading: /Development/player/js/utils/tests/test_Ajax.html
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 588: invalid property id
 [java] js:             throws: function throws(error, message) {
 [java] js: ..................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 588: syntax error
 [java] js:             throws: function throws(error, message) {
 [java] js: ...................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 589: missing ; before statement
 [java] js:                 if (typeof error == "string") {
 [java] js: ..............................................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 590: syntax error
 [java] js:                     this.exception = new Error(message);
 [java] js: .........................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 592: missing ) in parenthetical
 [java] js:                 } else if (!error) {
 [java] js: ......................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 593: syntax error
 [java] js:                     this.exception = new Error("Error");
 [java] js: .........................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 594: missing ) in parenthetical
 [java] js:                 } else {
 [java] js: ......................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 595: syntax error
 [java] js:                     this.exception = error;
 [java] js: .........................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 596: syntax error
 [java] js:                 }
 [java] js: ................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 599: syntax error
 [java] js:             },
 [java] js: ............^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 601: syntax error
 [java] js:             callsArg: function callsArg(pos) {
 [java] js: .....................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 602: missing ; before statement
 [java] js:                 if (typeof pos != "number") {
 [java] js: ............................................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 604: syntax error
 [java] js:                 }
 [java] js: ................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 606: syntax error
 [java] js:                 this.callArgAt = pos;
 [java] js: .....................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 608: syntax error
 [java] js:             },
 [java] js: ............^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 610: syntax error
 [java] js:             callsArgWith: function callsArgWith(pos) {
 [java] js: .........................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 611: missing ; before statement
 [java] js:                 if (typeof pos != "number") {
 [java] js: ............................................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 613: syntax error
 [java] js:                 }
 [java] js: ................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 615: syntax error
 [java] js:                 this.callArgAt = pos;
 [java] js: .....................^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 617: syntax error
 [java] js:             }
 [java] js: ............^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 619: syntax error
 [java] js:     }()));
 [java] js: ....^
 [java] js: "file:///Development/player/libs/sinon/sinon-1.0.0.js", line 626: syntax error
 [java] js: }(typeof sinon == "object" && sinon || null));
 [java] js: ^
 [java] could not load script  file:///Development/player/libs/sinon/sinon-1.0.0.js  
 [java]   InternalError: Compilation produced 22 syntax errors. 
 [java] error loading script  [object HTMLScriptElement]   InternalError: Compilation produced 22 syntax errors. 

Chaining expectations returns incorrect error

Assume a test containing the following chained expectations is passing:

mock.expects('render').once().calledWith(arg1);

Now when changing the calledWith expectation parameter to break the test:

mock.expects('render').once().calledWith(arg2);

Sinon is returning the wrong error, saying that the render method was expected to be called once, but was called 0 times. The correct error should be that the render method was not called with the correct arguments.

readyStateChange is not called when useFilters is true.

fake_xml_http_request.js

        open: function open(method, url, async, username, password) {
            ...

            if(sinon.FakeXMLHttpRequest.useFilters === true) {
                var xhrArgs = arguments;
                var defake = some(FakeXMLHttpRequest.filters,function(filter) {
                    return filter.apply(this,xhrArgs)
                });
                if (defake) { sinon.FakeXMLHttpRequest.defake(this,arguments); }
            } else {
                this.readyStateChange(FakeXMLHttpRequest.OPENED);
            }
        },

I think "this.readyStateChange" should be called when "useFilters" is true and "defake" is false.

setTimeout parameters are ignored

Sinon seems to ignore optional function parameters passed to setTimeout:

var clock = sinon.clock.create();

clock.setTimeout(function(i) {
    console.log(i);
}, 1, 'string');

clock.tick(2);

Expected output: string
Actual output: undefined

fakeServer swallows exceptions in onreadystatechange handler

When using fakeServer, and something causes an exception in onreadystatechange, or code called from it:

Expected:

  • Exceptions are logged to the console in the same way they would as if not running with fakeServer
  • If an exception occurs in a onreadystatechange handler, it should not prevent onreadystatechange to be triggered for other ready states

Actual:

  • Exceptions are silently caught and ignored
  • Processing of request ends, without ever reaching ready state 4.

Bug occurs because of this: https://github.com/cjohansen/Sinon.JS/blob/master/lib/sinon/util/fake_server.js#L182
Example here: http://jsfiddle.net/S6VYe/3/

FWIW, there are a few other instances of "catch (e) {}" in sinon. They are almost certainly wrong as well.

stub with custom return

Hi, I need to create a stub for a function, this stub should replace original function and use my stub function instead, for example:

s = sinon.stub(obj, "hello");
s.return(function(a) { return a; });

In current API I can't found anything to do something like this... the "return" of stub only accepts a final value...

There is anyway to accomplish it? Maybe on future versions?

About stub.callsArg throws error if the arg is not callable

Sometimes I wish stub.callsArg would not throw error if the arg is not callable. For example:

If I have this obj:

obj = {
    data: 1,

    isDataValid: function(valid, invalid) {
        // Async method that calls its first arg if data is valid otherwise calls its second
    },

    processData: function() {
        this.isDataValid(function() {
            ++this.data;
        });
    }
}

And I'd like to make sure that if data isn't valid, it's not processed

sinon.stub(obj, 'isDataValid');
obj.isDataValid.callsArg(1);
obj.processData();
assertEqual(obj.data, 1);

It apparently doesn't work because obj.processData() will throw error.

It would be great if there exists a stub API that calls the arg only if it's callable. Do you think it's possible? If it is, should we modify stub.callsArg() or introduce a new API? What would the new API be?

sinon.testCase should return result of test

if you include setUp or tearDown, sinon.testCase does not pass on the result of the test. some testing frameworks use the return result of the test.

the fix is simple, not worth a pull request:

function createTest(property, setUp, tearDown) {
    return function () {
        if (setUp) {
            setUp.apply(this, arguments);
        }

        var exception, result;

        try {
            result = property.apply(this, arguments);
        } catch (e) {
            exception = e;
        }

        if (tearDown) {
            tearDown.apply(this, arguments);
        }

        if (exception) {
            throw exception;
        }
        return result;
    };
}

Standalone version is broken with RequireJS

Although ease fixable by changing this:

if (typeof require == "function") {
    var sinon = require("sinon");
    ...

into this

if (typeof module == "object" && typeof require == "function") {
    var sinon = require("sinon");
    ...

Stubbing a global function does not work in IE

Something like this

this.stub(window, "funcName");

throws Object doesn't support this property or method in IE 8.
I tracked it down to line 98 in sinon-1.2.0.js where hasOwnProperty is called on the given object. window does not support this method in IE on the window object .... for whatever silly reason.

Changing the line to the following fixes it:

var owned = object === window || object.hasOwnProperty(property);

Can't checkout / commit from / to GitHub @work, so I can't write a test case and contribute the fix. I might find the time at home eventually.

assert.calledOnceWithMatch

assert.match is the best thing way before sliced bread, and I want it with everything. But most of all I want it with assert.calledOnceWith.

The usecase that prompted this issue was todays snafu:

fs.createReadStream(__dirname + '/blank-config-file.js');

stubbing out this so-and-so makes for some unwieldy getCall and args incantations. Sinon is for beauty, and let me tell you - this code I just wrote isn't gonna win any pageants. :)

server.respondWith function - TypeError

I'm getting a TypeError while passing a function to server.respondWith

window.server = sinon.fakeServer.create();

server.respondWith(function(){
  console.log(arguments);
})

TypeError: Fake server response body should be string, but was function

This seems to be the code that causes this
lib/sinon/util/fake_server.js

 respondWith: function respondWith(method, url, body) {
            if (arguments.length == 1) {
                this.response = responseArray(method);
            }
            ...

function responseArray(handler) {
        var response = handler;

        if (Object.prototype.toString.call(handler) != "[object Array]") {
            response = [200, {}, handler];
        }

        if (typeof response[2] != "string") {
            throw new TypeError("Fake server response body should be string, but was " +
                                typeof response[2]);
        }

        return response;
    }

Seems like it doesn't support passing functions into .respondWith is this the attended behavior?

The handler above is really an Array

clock.tick() silently catches exceptions

I want to test some code where a timeout throws an exception. However, it seems that sinnon's fake timers silently swallow any exception they encounter:

https://github.com/cjohansen/Sinon.JS/blob/master/lib/sinon/util/fake_timers.js#L173-179

I'd love to send a patch for this (if you want), but I couldn't get the test suite to run:

make test
jstestdriver --tests all --reset
Unexpected Runner Condition: Connection error on: sun.net.www.protocol.http.HttpURLConnection:http://localhost:4224/jstd/proxy
 Use --runnerMode DEBUG for more information.

useFakeTimers(now) can't return fake time when I call new Date()

I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.

But the following code doesn't work for me.

sinon.useFakeTimers(new Date(2011,9,1));

//expect : 'Sat Oct 01 2011 00:00:00' ,
//result : 'Thu Oct 27 2011 10:59:44โ€˜
var d = new Date();

dispatch readystatechange?

I'm trying to use sinon with sproutcore to stub xhr requests.

It seems to mostly integrate fine except that sproutcore relies on the readystatechange event being dispatched by the XMLHttpRequest - which sinon.FakeXMLHttpRequest does not seem to do.

See:

Any ideas about this? If you could hint me at how to implement this I'd happily give it a try.

spy.args can give inaccurate results by referencing arguments

To see the issue: http://jsfiddle.net/93EVL/1/

Issue:
I ran into an issue today where sinon.args was not returning results I was expected. Seems like we would always want to know exactly what a function is called with.

Backstory:
We have some code where a function receives an options object, and one of the key is {retries: 3}. Our code will decrement retries, then call another function (that we are spying on) passing to it the options object, until retries === 0.
When all is said and done I would have expected to see:

ourSpiedOnFunction.args === [{retries: 2}, {retries: 1}, {retries: 0}]

but instead got:

ourSpiedOnFunction.args === [[retries: 0}, {retries: 0}, {retries: 0}]

So, it seems like sinon holds onto the arguments by reference, which is causing this issue. Demonstration of the issue here: http://jsfiddle.net/93EVL/1/

Standalone: sinon.test returns function as opposed to executing test code

The expected usage:

it "should check if user is set", -> sinon.test ->
  User = current: this.spy()
  app = new AppController
  ( expect User.current.called ).toBeTruthy()

Does nothing unless sinon.test is wrapped in function invocation:

it "should check if user is set", -> (
  sinon.test ->
    User = current: this.spy()
    app = new AppController
    ( expect User.current.called ).toBeTruthy()
)()

The reason becomes apparent when examining how sinon.test is defined - it returns function.

Wrap ES5 getters and setters

var o = {
  get foobar() { return 'foobar' },
  set foobar(s) { throw 'bzzt!' },
  foo: function() { return 'foo' },
  bar: 'bar'
}; // -> { foobar: [Getter/Setter], foo: [Function], bar: 'bar' }

sinon.mock(o).expects('foobar').returns('woohoo'); // doesn't because sinon.wrapMethod() does an object[property] which accesses the getter which returns a string

To support getters and setters you need to do a Object.getOwnPropertyDescriptor(obj, prop) for the object and then a recursive Object.getPrototypeOf(obj) if it doesn't exist, the descriptor has a 'get' and 'set' property where they are defined.

But, you may want to mock out just the getter or just the setter or both, so how do you specify that? Some options:

mock(o).expects('foobar'); // ambiguous, the setter? getter? or both?
mock(o).expects('get foobar'); // ambiguous, there may be a legitimate property named "get foobar"
mock(o).expectsGet('foobar'); // clear but more code in Sinon and more to document ?
mock(o).expectsSet('foobar'); // ditto

And also, do you have a convention in place already for dealing with features that may not be present in the current environment? If someone tries to do this in IE6 what should happen?

Stub/Spies direct onto an Object

Hi, I'm new to BDD/TDD, Sinon.js is great btw :)

I'm using Sinon.js with Mocha & Node.js, and I was wondering if there was a way to add spies/stubs onto existing objects... so that any reference to that object now includes those spies... for example...

module.js

module.exports = function(){
}

subject.js

x = require('./module.js');
x()

test_subject.js

describe('subject', function(){
  it('should call x()', function(){
    x = require('./module.js');
    sinon.spy(x);
    require('./subject.js');
    assert.equal(x.called, true);  // failed
  });
})

might not be possible, thanks :)

just wanted to note that if module.js returns an object, it'll be spyable...

// module.js
exports.x = function(){
}

// subject.js
module = require('./module.js');
module.x();

// test_subject.js
module = require('./module.js');
sinon.spy(module, 'x');
require('./subject.js');
assert.equal(module.x.called, true);  // passes

related question for me, if X was instead a class, would it be possible? For example

// module.js
module.exports = function(){
}

// subject.js
X = require('./module');
new X;

// test_subject.js
X = require('./module');
sinon.spy(X, 'constructor');  // or sinon.spy(X.prototype, 'constructor'); ??
require('./subject');
assert.equal(X.calledWithNew(), true);

My understanding of how instances are created might be completely wrong. But is it correct that there is no way to turn an object into a spy, but instead have to create a new object, that's a spy? For example:

x = function(){};
sinon.spy(x);  // x isn't spied
y = sinon.spy(x)  // y is spied

x = {y:function(){}}
sinon.spy(x, 'y');  // x.y is spied, works; can the above work the same way?

Thank you :)

No integration hook for mock.js err()

I'm currently working on a NodeJS testing framework, which will have pluggable support for mocking frameworks.

The available SinonJS hooks make this rather easy, and I've got the sandbox and assertions working nicely by overriding sinon.assert.fail - however failures from mocks don't use this method, and simply call a private method to throw their exception.

It would be nice if mocks could fail using assert.fail, but if this doesn't mesh with the way things are arranged at the moment then it would be helpful to expose the failure method used in mocks/expectations

I'm happy to submit a patch if you'd like to provide some pointers on what approach to take.

Node.js and useFakeTimers()

Using the following code:

sinon = require "sinon"

console.log( new Date() )

sandbox = sinon.sandbox.create()
sandbox.useFakeTimers()

now = new Date()

console.log( now )
console.log( now.getTime() )
console.log( now.getFullYear() )

sandbox.restore()

console.log( new Date() )

I get this output:

Sun, 20 Nov 2011 19:49:52 GMT
{}
0
1970
Sun, 20 Nov 2011 19:49:52 GMT

It seems that sinon isn't doing the right thing with regards to the Date constructor.

Child properties of functions disappear when function is stubbed

I have encountered a situation in which Sinon doesn't quite play nicely with the way I've 'namespaced' the JavaScript in a current project. While there may be issues with the namespacing implementation, I thought it may be something you'd want to support in any case. The issue is demonstrated in this gist, but in short occurs when stubbing out a function that has child properties declared on it. When stubbed, the child properties are not carried over to the stub and therefore are undefined until the original function is restored, which has proved troublesome.

I have patched this (rather roughly) locally for the time being, but would be more than willing to clean that up and submit a patch in the next day or two if you'd like. I've really enjoyed working with Sinon, the framework has proved very flexible and the documentation well-written and helpful.

timers does not work with Date.now in IE8

When you use a polyfill for Date.now, like MooTools or ES5-shim does, the fake timer does not work in (native) IE8.
Probably it's because Sinon.JS feature checks if Date.now is available, but the polyfill is loaded after Sinon.JS is loaded.

Example: http://jsfiddle.net/arian/dhEbb/2/

Don't know if an exception can be made so when useFakeTimer is used, it will check if Date.now exists, or perhaps implementing Date.now anyway (so removing this check: https://github.com/cjohansen/Sinon.JS/blob/master/lib/sinon/util/fake_timers.js#L222), which works for me too.

mock.verify() issue in nodejs with vows

Using nodejs 0.4.7 and vows 0.5.8, I created a spec containing:

var myAPI = { method: function () {} };

var spy = sinon.spy();
var mock = sinon.mock(myAPI);
        
mock.expects('method').never();
mock.verify();

When I run the tests, I get the following error:

TypeError: Cannot read property 'toString' of undefined
    at Function.toString (/usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:388:44)
    at /usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:108:50
    at each (/usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:45:17)
    at /usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:104:21
    at each (/usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:45:17)
    at Object.verify (/usr/local/lib/node/.npm/sinon/1.1.0/package/lib/sinon/mock.js:103:17)
    at Object. (/Users/markstory/Sites/node_bot/test/client-test.js:69:9)
    at runTest (/usr/local/lib/node/.npm/vows/0.5.8/package/lib/vows.js:95:26)
    at EventEmitter. (/usr/local/lib/node/.npm/vows/0.5.8/package/lib/vows.js:73:9)
    at EventEmitter.emit (events.js:81:20)

The offending line attempts to call sinon.spyCall.toString.call() however that object doesn't seem to exist when sinon has been loaded through node's require().

Adding the sinon.spyCall assignment when in a CommonJS module seems to have fixed the issue for me.

fakeServer.respond swallows assertions

The try/catch block in fakeServer.processRequest is swallowing all exceptions which means that failed assertions cannot be detected within a response function provided to respondWith. I am trying to test the body of the request that is being sent to the server. Is there any other way to do this?

Fake properties

More of a question than an issue per-se, but is there any way to spy/stub/mock property access on objects/mocks?

Here's an example cribbed straight from some code I'm working on:

this.example("assert is a reference to nodespec.assert", function() {
    var real_assert = this.assert;
    var fake_assert = new Object;
    require('../lib/index').assert = fake_assert;
    real_assert.strictEqual(this.context.assert, fake_assert);
    require('../lib/index').assert = real_assert;
    this.done();
});

It's a little bit opaque, but the idea is that I need to change the assert property of the module in '../lib/index' to be a fake, and then restore it afterwards.

As far as I can tell Sinon almost exclusively deals with functions - not whole objects or properties.

Put all documentation on one page

The current setup with "high-level" documentation on one page and API reference on another is just confusing. Put it all on one page, and structure the documentation around following sections (for each concept):

What are test stubs?
When to use stubs?
Examples
Reference

calledWith / calledWithExactly don't check references

Hi,

so I've turned my window shopping for mocking libraries into actual usage : ). One thing I just ran into is that calledWith and calledWithExactly check for deep equality instead of references. This is a little hard to get used to because I often check for object references when passing stuff around.

This also seems to be inconsistent with other API calls spy.returned() which performs a reference check (even so the docs claim it to be a deep equal check):

https://github.com/cjohansen/Sinon.JS/blob/master/lib/sinon/spy.js#L273

So I'm wondering if there is a reason for this behavior / if it would make sense to provide methods for both deep equality as well as reference checks?

--fg

Assert never called with arguments

It would be a nice extension of the assert API to be able to check whether a spy was never called with a specific argument list:

sinon.assert.neverCalledWith(spy, "some", "arguments")

Cannot run jstestdriver on latest OS X install with fresh dev-tools

After setting up a new machine with Snow Leopard and latest XCode from App Store, I get the following when running
jstestdriver --port 4224

NOTE: Gem::Specification#default_executable= is deprecated with no replacement. It will be removed on or after 2011-10-01.
Gem::Specification#default_executable= called from /Library/Ruby/Gems/1.8/specifications/rubygems-update-1.8.2.gemspec:11.

However, jsautotest works fine when I start JSTD myself - even though it shows the same message.

-Max

fake server does not respond to JSONP XHR

I have written it a number of ways and none of them are working. The request is going to the actual address. Is there an issue with my code or is this a bug?

server = sinon.fakeServer.create()
url = "http://fake.com/foo/bar"
# set up server
server.respondWith("GET", url, [200, { "Content-Type": "application/json" }, '[{ id: 12, name: "Hey there" }]'])

# spy 
callback = sinon.spy()

# remote call
$.get(url, {}, ->
            console.log "hi"
            callback.call() 
     , "jsonp"  
    )
# respond from fake server
server.respond()

# assertions
assert(callback.calledWith([{ id: 12, comment: "Hey there" }])).isTrue("Search run via ajax on a remote resource")

About stub.callsArg throws error if the arg is not callable

Sometimes I wish stub.callsArg would not throw error if the arg is not callable. For example:

If I have this obj:

obj = {
    data: 1,

    isDataValid: function(valid, invalid) {
        // Async method that calls its first arg if data is valid otherwise calls its second
    },

    processData: function() {
        this.isDataValid(function() {
            ++this.data;
        });
    }
}

And I'd like to make sure that if data isn't valid, it's not processed

sinon.stub(obj, 'isDataValid');
obj.isDataValid.callsArg(1);
obj.processData();
assertEqual(obj.data, 1);

It apparently doesn't work because obj.processData() will throw error.

It would be great if there exists a stub API that calls the arg only if it's callable. Do you think it's possible? If it is, should we modify stub.callsArg() or introduce a new API? What would the new API be?

Dependency between tests using jQuery .animation with Duration

I'm having a hard time testing animation tests and I think I boiled the problem to a dependency issue.

It seems that if we add the duration to the animation, the following tests are affected. In the following example both tests fail because of the 1000 duration value on the first test. But if I remove that value, both tests pass.

    describe("Test animation with duration", function(){

        beforeEach(function(){                      
            this.clock = sinon.useFakeTimers();
        }); 

        afterEach(function (){
            this.clock.restore();
        });         

        it("test should animate element over 1000ms", function(){
            var el = $("<div'></div>");
            el.appendTo(document.body);

            el.animate({ height: "300px", width: "200px" },1000); // Notice the duration
            this.clock.tick(510);
            expect(el.css("height")).toBe("300px");
            expect(el.css("width")).toBe("200px");
        });     

        it("test should animate element over 500ms", function(){
            var el = $("<div></div>");
            el.appendTo(document.body);

            el.animate({ height: "300px", width: "200px" });
            this.clock.tick(510);
            expect(el.css("height")).toBe("300px");
            expect(el.css("width")).toBe("200px");
        });             

    });

Can't use sinon.spy on Array.prototype.push

If I use sinon.spy on Array.prototype.push, I get this error in Chrome when launching the test:

Error in Chrome 14.0.835.163

Chrome 14.0.835.163 Windows: Run 20 tests (Passed: 15; Fails: 0; Errors 5) (40.00 ms)
  error loading file: /test/libs/fakeLab.js:0: Script error.
  Test.test should call Array.prototype.push one time (15.00 ms): : 
    : 

As you can see there is no information about this error. I found what was happening using Firefox modifying the User Agent to simulate Chrome browser.

Then I get this error:

too much recursion

invoke(push,[object Array],[object Array])@ /libs/sinon/sinon.js:387

proxy([object Array])@/libs/sinon/sinon.js:369

Include sinon on documentation pages

Firstly, thanks for making sinon. It makes mocking, stubbing and spying an absolute pleasure.

I have a pretty small request. This might not be the best place for it.

Backbone and Underscore both include their script on the page, so while I read their documentation I can experiment with the library in the web inspector's REPL.

This makes exploring the API while reading the documentation an absolute breeze. It also allows users to experiment with your module's interface with minimal effort on their part.

Thanks for considering,

-n-time

Failing tests cause TypeError in JsTestDriver

When "globalizing" assertions with sinon.assert.expose(this) as described in Sinons documentation, a failing assertion causes a TypeError.

Example:

"test something": function() {
    var stub = this.stub();
    assertCalled(stub);
}

Running the test with JsTestDriver causes an error:

TypeError: Cannot read property 'fail' of undefined

The test should cause an AssertError with a proper error message, as sinon.assert.called does.

Tested with JsTestDriver 1.2.2 and 1.3.3d and Sinon 1.2.0. Full code example and output in this Gist: https://gist.github.com/1472854

sinon in npm registry broken with node 0.6.5

node.js finally removed require.paths, the sinon (and sinon-nodeunit) in the NPM registry still have it. Git clone directly into the node_modules folder works fine, please republish.

Here's the output

uncaught undefined: Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
at Function. (module.js:376:11)
at Object. (/Users/shawn/Developer/node/nodeproj1/node_modules/sinon-nodeunit/deps/sinon/lib/sinon.js:208:12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.