Code Monkey home page Code Monkey logo

jasmine-sinon's Introduction

Jasmine matchers for Sinon.JS

Build Status

jasmine-sinon provides a set of custom matchers for using the Sinon.JS spying, stubbing and mocking library with Jasmine BDD.

Instead of:

expect(mySinonSpy.calledWith('foo')).toBeTruthy();

you can say:

expect(mySinonSpy).toHaveBeenCalledWith('foo');

This is not only nicerer to look at in your purdy specs, but you get more descriptive failure output in your Jasmine spec runner.

Instead of:

Expected false to be truthy.

you get:

Expected spy "mySpy" to have been called with "foo".

Jasmine 1.x / 2.x compatibility

If you are using Jasmine 1.x, use the latest 0.3.x release. For Jasmine 2, use 0.4 or above.

Installation

Direct include

Just include lib/jasmine-sinon.js in your Jasmine test runner file. Don't forget to include sinon.js.

Add it to jasmine.yml. Don't forget to include sinon.js.

Node.js / NPM

npm install jasmine-sinon --save-dev

Then, in your jasmine spec:

var sinon = require('sinon');
require('jasmine-sinon');

Using Bower

bower install jasmine-sinon --save-dev

Then, include components/jasmine-sinon/index.js in your test runner.

Sinon.JS matchers

In general, you should be able to translate a Sinon spy/stub/mock API method to a jasmine-sinon matcher by prepending toHaveBeen to the front of the method name. For example, the Sinon.JS spy method called becomes toHaveBeenCalled. There are one or two exceptions to this rule, so the full list of matchers is given below.

Sinon.JS property / method jasmine-sinon matcher
called toHaveBeenCalled()
calledOnce toHaveBeenCalledOnce()
calledTwice toHaveBeenCalledTwice()
calledThrice toHaveBeenCalledThrice()
calledBefore() toHaveBeenCalledBefore()
calledAfter() toHaveBeenCalledAfter()
calledOn() toHaveBeenCalledOn()
alwaysCalledOn() toHaveBeenAlwaysCalledOn()
calledWith() toHaveBeenCalledWith()
alwaysCalledWith() toHaveBeenAlwaysCalledWith()
calledWithExactly() toHaveBeenCalledWithExactly()
alwaysCalledWithExactly() toHaveBeenAlwaysCalledWithExactly()
calledWithMatch() toHaveBeenCalledWithMatch()
alwaysCalledWithMatch() toHaveBeenAlwaysCalledWithMatch()
calledWithNew toHaveBeenCalledWithNew() >=v0.4
neverCalledWith toHaveBeenNeverCalledWith() >=v0.4
neverCalledWithMatch() toHaveBeenNeverCalledWithMatch() >=v0.4
threw() toHaveThrown()
alwaysThrew() toHaveAlwaysThrown()
returned() toHaveReturned()
alwaysReturned() toHaveAlwaysReturned()

These matchers will work on spies, individual spy calls, stubs and mocks.

You can use Jasmine spies alongside your Sinon spies. jasmine-sinon will detect which you're using and use the appropriate matcher.

You can also use Jasmine's fuzzy matchers any() and objectContaining() in expectations, e.g.

expect(spy).toHaveBeenCalledWith(jasmine.any(Date));
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({name: 'froots'}))

Contributors

Thanks to:

  • @aelesbao for Exception matchers
  • @theinterned for, er, match matchers
  • @milichev for graceful spy matchers
  • @reinseth for Jasmine fuzzy matcher support
  • @stoodder for initial Jasmine 2.0 support work

jasmine-sinon's People

Contributors

froots avatar milichev avatar reinseth avatar theinterned 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

jasmine-sinon's Issues

Compatible with sinon 1.8.x?

Our Bower build system freaks out when we try to use 'sinon' 1.8.1, because 'jasmine-sinon' specifies ~1.7.1 (meaning anything in the 1.7.x range) as a depedency.

Is there a reason not to specify sinon >=1.7.1 instead?

"toHaveBeenCalledWithExactly" does not print actual calls

When using the toHaveBeenCalled... methods, the output looks like this:

Error: Expected spy "myMethod" (empty string)to have been called with exactly [ 'arg1', 1 ]

It would be helpful if (similar to Jest) the actual calls were printed as well.

Spying on existing methods does not work

sinon lets you spy on an existing method using the following syntax (from the sinonjs.org documentation):

sinon.spy(jQuery, "ajax");

unfortunately this does not work with jasmine-sinon. In the following test case I expect the test to complete successfully, but instead I get the result Error: Expected a spy, but got Function. Is the matcher a bit too clever? Is there a better way to decide if something is a spy, so this kind of syntax can work?

    describe("when spying on an existing object", function () {

        beforeEach(function () {

            this.object = {
                doSomething: function() {
                }
            };

            sinon.spy(this.object, 'doSomething');

            this.object.doSomething();
        });


        it("Should be a spy", function () {
            expect(this.object.doSomething).toHaveBeenCalled();
        });
    });

Incompatible with Jasmine 4

For more information, see "jasmine.pp is deprecated" in Upgrading to Jasmine 4.0. For example, the attached test outputs:

Failures:
1) spy should work with Jasmine
  Message:
    TypeError: jasmine.pp is not a function
  Stack:
        at Object.otherArgs (C:\Users\John\Documents\node-agwpe\node_modules\jasmine-sinon\lib\jasmine-sinon.js:48:24)
        at Object.message (C:\Users\John\Documents\node-agwpe\node_modules\jasmine-sinon\lib\jasmine-sinon.js:27:24)
        at compare (C:\Users\John\Documents\node-agwpe\node_modules\jasmine-sinon\lib\jasmine-sinon.js:198:30)
        at <Jasmine>
        at UserContext.<anonymous> (C:\Users\John\Documents\node-agwpe\spec\agwpe\jasmine-sinonSpec.js:26:27)
        at <Jasmine>

jasmine-sinonSpec.js.txt

Receiving "Typeerror: cannot read property 'ToHaveBeenCalled' of undefined"

Just did a bower reinstall of jasmine#2.0.0, sinon#1.9.1, jasmine-sinon#0.4.0.

Stacktrace (edited for readability)

TypeError: Cannot read property 'toHaveBeenCalled' of undefined
        at createMatcher (/jasmine-sinon/lib/jasmine-sinon.js:168:36)
        at createJasmineSinonMatchers /jasmine-sinon/lib/jasmine-sinon.js:209:51)
        at null.<anonymous> (/jasmine-sinon/lib/jasmine-sinon.js:215:25)

Thanks!

Sinon.js and Rhino issue with Fake Timers

This is continuation of my blog post about Sinon.js and Fake timers: Headless JavaScript testing, Sinon.js, Fake Timers and Rhino.

As promised, I've made environment with Rhino and Sinon.js where test for Fake Timers is not work properly (download). To execute tests use ./runtests.sh, you need to have Java.

I found debugger for Rhino and I will try to solve this issue but I don't have enough experience to do it efficiently.

Here is output:

Maxs-MacBook-Air:Sinon-Rhino maxk$ ./runtests.sh 
[  Envjs/1.6 (Rhino; U; Mac OS X x86_64 10.7.3; en-US; rv:1.7.0.rc2) Resig/20070309 PilotFish/1.2.13  ]
Loading: runner.html
Runner Started.
Timers Issue Test : Failing timer test ... 
Failed.
Timers Issue Test: 1 of 4 passed.
Runner Finished.
1 spec, 1 failure in 0.092s.

Older version of jasmine-sinon being pulled in ?

Sorry - very much a noob with Jasmine and sinon. Using this in an angular project to run javascript testing and I am hitting the error:

ERROR: TypeError: 'undefined' is not an object (evaluating 'jasmine.Matchers.prototype')

I have downloaded the latest jasmine-sinon.js but the error persists.

If I run my jasmine specs in the browser, however, it appears to be looking at an OLDER version of jasmine-sinon because the line in question looks like the older code (based on a closed issue I reviewed):

(lines 25, 26):
    getMatcherFunction = function(sinonName, matcherName) {
      var original = jasmine.Matchers.prototype[matcherName];

So, I suspect jasmine, rails, or something else is still using the old version.
Here is what I'm running (bundle list):
jasmine-core-2.0.0
jasmine-rails-0.9.0

Any suggestions?

Thanks!

outdated dependencies

├─┬ jasmine-sinon#0.4.0
│ ├── jasmine#2.0.4 (latest is 2.3.4)
│ └── sinonjs#1.14.1 (1.17.1 available)

Can jasmine-sinon be used in a Typescript project?

Hi all --

I was excited to find this module, and I'm eager to put it to use. However, I can't seem to get jasmine-sinon incorporated into my Typescript unit tests such that they work.

import * as sinon from 'sinon';
import * as jasmineSinon from 'jasmine-sinon';

describe('Experiment', () => {
  const sandbox = sinon.sandbox.create();
  const mockService = sinon.createStubInstance(SomeService);

  beforeEach(() => {
    mockService.getSomeValue = sandbox.stub().returns('blah');
  });

  it('should do a thing', () => {
    expect(mockService.getSomeValue).toHaveBeenCalledOnce();
  }

This results in the following compiler output:

Error: blah.component.spec.ts (119,58): Property 'toHaveBeenCalledOnce' does not exist on type 'Matchers'.,blah.component.spec.ts (119,58): Property 'toHaveBeenCalledOnce' does not exist on type 'Matchers'.

I'd like to know if I'm just doing something wrong, or if this just won't work in a Typescript project. Any tips, pointers, and/or working example would be much appreciated.

Thanks!

Add TypeScript typings

To use jasmine-sinon in a TypeScript project, it is necessary to add a custom typings file. It would be easier for adopters if this was provided as part of the package.

Example jasmine-sinon.d.ts:

declare namespace jasmine {
  export interface Matchers<T> {
    toHaveBeenCalled(): boolean;
    toHaveBeenCalledOnce(): boolean;
    toHaveBeenCalledTwice(): boolean;
    toHaveBeenCalledThrice(): boolean;
    toHaveBeenCalledBefore(anotherSpy: any): boolean;
    toHaveBeenCalledAfter(anotherSpy: any): boolean;
    toHaveBeenCalledOn(obj: any): boolean;
    toHaveBeenAlwaysCalledOn(obj: any): boolean;
    toHaveBeenCalledWith(...args: any[]): boolean;
    toHaveBeenAlwaysCalledWith(...args: any[]): boolean;
    toHaveBeenCalledWithExactly(...args: any[]): boolean;
    toHaveBeenAlwaysCalledWithExactly(...args: any[]): boolean;
    toHaveBeenCalledWithMatch(...args: any[]): boolean;
    toHaveBeenAlwaysCalledWithMatch(...args: any[]): boolean;
    toHaveBeenCalledWithNew(): boolean;
    toHaveBeenNeverCalledWith(...args: any[]): boolean;
    toHaveBeenNeverCalledWithMatch(...args: any[]): boolean;
    toHaveThrown(error: any): boolean;
    toHaveAlwaysThrown(error: any): boolean;
    toHaveReturned(returnValue: any): boolean;
    toHaveAlwaysReturned(returnValue: any): boolean;
  }
}

There is no license

I am hoping to use this at work but need to know what the license is. Is it MIT like Jasmine?

p.s. thanks for the tool, looks very cool!

1 error on Jasmine 2.0.0rc5

screen shot 2013-11-13 at 12 52 02 am
screen shot 2013-11-13 at 12 51 56 am

Uncaught TypeError: Cannot read property 'prototype' of undefined 

(Jasmine.Matchers do not exist anymore)

Travis builds for pull request fail because of dependencies can't be installed

Subject says it: travis fails on node 0.8 target because dependecies can't be installed:

npm ERR! Error: No compatible version found: date-now@'^0.1.4'

npm ERR! Valid install targets:

npm ERR! ["0.1.0","0.1.1","0.1.3","0.1.2","0.1.4","1.0.0","1.0.1"]

npm ERR! at installTargetsError (/home/travis/.nvm/v0.8.28/lib/node_modules/npm/lib/cache.js:719:10)

npm ERR! at /home/travis/.nvm/v0.8.28/lib/node_modules/npm/lib/cache.js:641:10

npm ERR! at saved (/home/travis/.nvm/v0.8.28/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:138:7)

npm ERR! at Object.oncomplete (fs.js:302:15)

npm ERR! If you need help, you may report this log at:

npm ERR! http://github.com/isaacs/npm/issues

npm ERR! or email it to:

npm ERR! [email protected]

Update to jasmine 2.0 ?

Hi!

I want update to jasmine 2.0, but jasmine-sinon has requirement :

jasmine-sinon#0.3.1 depend on jasmine#~1.3.1 which resolved to 1.3.1

Can I use the jasmine sinon with jasmine 2.0 ?

"(empty string)" printed in failed expectation

Using [email protected], [email protected]

Steps to reproduce:

const spy = sinon.spy(() => {});
expect(spy).toHaveBeenCalledWith(true);

Output:

Expected spy "spy" (empty string)to have been called. "spy" was called 0 times.

The cause seems to be that in messageUtils, this block here:

    expectedSpy: function(pass, spy, txt) {
      var not = (pass ? 'not ' : '');
      var printf = spy.printf || sinon.spy.printf;
      return printf.call(spy, 'Expected spy "%n" %1%2', not, txt);
    },

is using printf which in sinon 2.4.1 uses formatio.ascii which prints an empty string as (empty string).

Why use the past perfect tense in the passive voice?

Out of curiosity, why did you opt for matchers that use the past perfect tense in the passive voice instead of simply the present tense in the passive voice? I ask because both convey pretty much the same meaning, but the present tense is easier to read and reason about. It also requires less typing to boot.

e.g.

expect(mySpy).toBeCalledOnce() vs. expect(mySpy).toHaveBeenCalledOnce();

expect(mySpy).toBeCalledWith(1) vs. expect(mySpy).toHaveBeenCalledWith(1);

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.