Convert Figma logo to code with AI

sinonjs logosinon

Test spies, stubs and mocks for JavaScript.

9,645
771
9,645
37

Top Related Projects

22,590

☕️ simple, flexible, fun javascript test framework for node.js & the browser

15,742

Simple JavaScript testing framework for browsers and node.js

44,166

Delightful JavaScript Testing.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

8,106

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

13,784

🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API. Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.

Quick Overview

Sinon.js is a popular JavaScript testing library that provides standalone test spies, stubs, and mocks. It works with any unit testing framework and is designed to make testing JavaScript applications easier by allowing developers to simulate various scenarios and behaviors.

Pros

  • Versatile: Works with any JavaScript testing framework
  • Comprehensive: Offers spies, stubs, mocks, and fake timers
  • Easy to use: Simple API and clear documentation
  • No dependencies: Standalone library that doesn't require additional packages

Cons

  • Learning curve: Can be overwhelming for beginners due to its many features
  • Potential overuse: Developers might rely too heavily on mocks, leading to brittle tests
  • Performance: Heavy use of Sinon can slow down test execution
  • Limited TypeScript support: While improving, TypeScript integration is not as seamless as with some other libraries

Code Examples

  1. Creating a spy:
const spy = sinon.spy();
myFunction(spy);
console.log(spy.callCount); // Outputs the number of times the spy was called
  1. Stubbing a method:
const stub = sinon.stub(object, 'method').returns('stubbed value');
console.log(object.method()); // Outputs: 'stubbed value'
stub.restore(); // Restores the original method
  1. Using a fake timer:
const clock = sinon.useFakeTimers();
setTimeout(() => console.log('Hello'), 1000);
clock.tick(1000);
// 'Hello' is logged immediately, without waiting 1 second
clock.restore();

Getting Started

To use Sinon.js in your project, first install it via npm:

npm install sinon --save-dev

Then, in your test file, require Sinon and start using it:

const sinon = require('sinon');

describe('My test suite', () => {
  it('should spy on a function', () => {
    const spy = sinon.spy();
    // Use the spy in your test
    assert(spy.calledOnce);
  });
});

For browser-based projects, you can include Sinon via a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/15.0.1/sinon.min.js"></script>

Competitor Comparisons

22,590

☕️ simple, flexible, fun javascript test framework for node.js & the browser

Pros of Mocha

  • More comprehensive test framework with built-in test runner
  • Supports various assertion libraries and reporting formats
  • Flexible and extensible with plugins and custom reporters

Cons of Mocha

  • Requires additional assertion library for most testing scenarios
  • Steeper learning curve for beginners due to more features and options

Code Comparison

Mocha test example:

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

Sinon test example:

it('calls onClick callback', function () {
  var callback = sinon.spy();
  var button = shallow(<Button onClick={callback} />);
  button.find('button').simulate('click');
  assert(callback.calledOnce);
});

Mocha is a full-featured testing framework, while Sinon is primarily focused on spies, stubs, and mocks. Mocha provides a structure for organizing and running tests, whereas Sinon offers tools for isolating code and simulating behavior. They are often used together in JavaScript testing environments, with Mocha providing the test runner and Sinon supplying powerful mocking capabilities.

15,742

Simple JavaScript testing framework for browsers and node.js

Pros of Jasmine

  • All-in-one testing framework with built-in assertion library and test runner
  • Easier setup and configuration for beginners
  • Extensive documentation and large community support

Cons of Jasmine

  • Less flexibility compared to modular testing setups
  • Slower test execution for large test suites
  • Limited mocking capabilities out of the box

Code Comparison

Jasmine:

describe('MyFunction', () => {
  it('should return true', () => {
    expect(myFunction()).toBe(true);
  });
});

Sinon:

const sinon = require('sinon');
const assert = require('assert');

describe('MyFunction', () => {
  it('should return true', () => {
    assert.strictEqual(myFunction(), true);
  });
});

Jasmine provides a more integrated approach with built-in assertion methods, while Sinon focuses on mocking and stubbing, often used alongside other testing frameworks and assertion libraries. Jasmine's syntax is generally more readable for beginners, but Sinon offers more powerful and flexible mocking capabilities.

Sinon is typically used in conjunction with other testing frameworks, providing specialized mocking, stubbing, and spying functionality. It's more modular and can be integrated into various testing setups. Jasmine, on the other hand, offers a complete testing solution out of the box, which can be advantageous for smaller projects or teams looking for a quick setup.

44,166

Delightful JavaScript Testing.

Pros of Jest

  • All-in-one testing solution with built-in assertion library, mocking, and code coverage
  • Snapshot testing for easy UI component testing
  • Parallel test execution for faster performance

Cons of Jest

  • Steeper learning curve due to more features and configuration options
  • Larger package size and potential overhead for simple projects
  • Less flexibility in choosing individual testing tools

Code Comparison

Sinon (mocking example):

const sinon = require('sinon');
const myObject = { myMethod: () => {} };
const mock = sinon.mock(myObject);
mock.expects('myMethod').once();
myObject.myMethod();
mock.verify();

Jest (mocking example):

const myObject = { myMethod: jest.fn() };
myObject.myMethod();
expect(myObject.myMethod).toHaveBeenCalledTimes(1);

Summary

Jest is a comprehensive testing framework that provides an all-in-one solution for JavaScript testing, including built-in assertion libraries, mocking, and code coverage. It excels in features like snapshot testing and parallel test execution. However, it may have a steeper learning curve and larger package size compared to Sinon.

Sinon, on the other hand, is a more focused library specifically for test spies, stubs, and mocks. It offers greater flexibility in choosing complementary testing tools but requires additional setup for a complete testing environment.

The choice between Jest and Sinon depends on project requirements, team preferences, and the desired level of control over the testing setup.

46,847

Fast, easy and reliable testing for anything that runs in a browser.

Pros of Cypress

  • End-to-end testing framework with a more comprehensive approach to web application testing
  • Built-in time travel and real-time reloads for easier debugging
  • Automatic waiting for elements and assertions, reducing flaky tests

Cons of Cypress

  • Limited to testing web applications only, unlike Sinon's broader JavaScript testing capabilities
  • Steeper learning curve due to its unique API and architecture
  • Slower test execution compared to unit tests with Sinon

Code Comparison

Cypress example:

describe('Login', () => {
  it('should log in successfully', () => {
    cy.visit('/login')
    cy.get('#username').type('user@example.com')
    cy.get('#password').type('password123')
    cy.get('button[type="submit"]').click()
    cy.url().should('include', '/dashboard')
  })
})

Sinon example:

describe('User Service', () => {
  it('should call the API with correct parameters', () => {
    const apiStub = sinon.stub(api, 'post')
    userService.login('user@example.com', 'password123')
    sinon.assert.calledWith(apiStub, '/login', {
      username: 'user@example.com',
      password: 'password123'
    })
  })
})
8,106

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

Pros of Chai

  • More extensive assertion library with multiple styles (expect, should, assert)
  • Better support for chaining assertions
  • Plugins ecosystem for extended functionality

Cons of Chai

  • Steeper learning curve due to multiple assertion styles
  • Slightly more verbose syntax for some assertions
  • Less focus on mocking and stubbing compared to Sinon

Code Comparison

Chai assertion:

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);

Sinon assertion:

assert.isString(foo);
assert.equals(foo, 'bar');
assert.equals(foo.length, 3);

Key Differences

  • Chai offers more flexibility in assertion styles, while Sinon focuses on simplicity
  • Sinon provides built-in mocking and stubbing capabilities, whereas Chai requires additional libraries
  • Chai's chaining syntax allows for more readable and expressive tests
  • Sinon's assertions are generally more concise but less customizable

Use Cases

  • Choose Chai for projects requiring diverse assertion styles and extensive test expressiveness
  • Opt for Sinon when mocking and stubbing are primary concerns, or when simpler assertion syntax is preferred

Both libraries are widely used and can be combined in projects to leverage their respective strengths.

13,784

🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API. Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.

Pros of Supertest

  • Specifically designed for testing HTTP servers and APIs
  • Provides a high-level abstraction for making HTTP requests and assertions
  • Integrates well with popular testing frameworks like Mocha and Jest

Cons of Supertest

  • Limited to HTTP-based testing scenarios
  • Less flexible for mocking and stubbing non-HTTP related functionality
  • Smaller ecosystem and community compared to Sinon

Code Comparison

Supertest:

const request = require('supertest');
const app = require('../app');

describe('GET /users', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/users')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

Sinon:

const sinon = require('sinon');
const user = require('../user');

describe('User', function() {
  it('calls save once', function() {
    const save = sinon.spy(user, 'save');
    user.setName('John');
    sinon.assert.calledOnce(save);
  });
});

Summary

Supertest excels in API and HTTP server testing, offering a straightforward approach to making requests and assertions. It's ideal for projects focused on web services. Sinon, on the other hand, provides a more comprehensive toolkit for general-purpose mocking, stubbing, and spying across various JavaScript environments. While Supertest is more specialized, Sinon offers greater flexibility for diverse testing scenarios beyond HTTP interactions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Sinon.JS
Sinon.JS

Standalone and test framework agnostic JavaScript test spies, stubs and mocks (pronounced "sigh-non", named after Sinon, the warrior).

npm version Sauce Test Status Codecov status OpenCollective OpenCollective npm downloads per month CDNJS version Contributor Covenant

Compatibility

For details on compatibility and browser support, please see COMPATIBILITY.md

Installation

via npm

$ npm install sinon

or via Sinon's browser builds available for download on the homepage. There are also npm based CDNs one can use.

Usage

See the sinon project homepage for documentation on usage.

If you have questions that are not covered by the documentation, you can check out the sinon tag on Stack Overflow.

Goals

  • No global pollution
  • Easy to use
  • Require minimal “integration”
  • Easy to embed seamlessly with any testing framework
  • Easily fake any interface
  • Ship with ready-to-use fakes for XMLHttpRequest, timers and more

Contribute?

See CONTRIBUTING.md for details on how you can contribute to Sinon.JS

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

Licence

Sinon.js was released under BSD-3

NPM DownloadsLast 30 Days