Test spies, stubs and mocks for JavaScript.

Overview

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 Join the chat at https://gitter.im/sinonjs/sinon Build status Sauce Test Status Codecov status OpenCollective OpenCollective npm downloads per month CDNJS version Contributor Covenant

Sauce Test Status

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 or drop by #sinon.js on irc.freenode.net:6667.

You can also search through the Sinon.JS mailing list archives.

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

Support us with a monthly donation and help us continue our activities. [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

Comments
  • Overridable `yields` vs sequential behavior

    Overridable `yields` vs sequential behavior

    Hi,

    in version 1.5.0 the semantics of calling yields multiple times changed from overriding former instructions to recording a sequence of values to be yielded sequentially (see #157).

    While the new behavior might be desirable in some cases, it makes one of our frequently applied test patterns almost impossible to use. We like to encapsulate the construction of commonly used stub objects in test helpers:

    function stubbedCollaborator() {
      return {
        doSomething: sinon.stub().yields([]),
        answer: sinon.stub().returns(42)
      };
    }
    

    Overriding the default behavior of individual stub methods allows each test to focus on the setup relevant to its intent. Since the change, this is no longer possible forcing the test to duplicate the complete stubbing setup if it needs to diverge from the default.

    I've looked into different ways to circumvent this issue, but have not yet come up with a side effect free solution.

    While I have to say the old API made more sense to me, I guess others are already depending on these new semantics. So I'd suggest adding a new way of calling yields which will be overridden by sequential calls. Something along the lines of yieldsDefault, while this might not be an intuitive name. Or an option on stub?

    I'd be really interested to hear your thoughts on this.

    Cheers Tim

    opened by tf 50
  • Add v2.0 Migration Guide

    Add v2.0 Migration Guide

    • [x] Add deprecation guide.
    • [x] Mark core utils as deprecated.
    • [x] Mark sinon.Event and friends as deprecated.
    • [x] Call out deprecation of legacy browsers

    Went through all the pull requests opened since the initial kick off of the CJSify work and tried to reason about the changes to the public API.

    Wasn't 100% where to the put the migration guide, but the docs folder felt like a good place :)

    opened by jonnyreeves 36
  • AMD: Built version from master is broken

    AMD: Built version from master is broken

    I've tried to create a pull request to verify that the API is working in AMD contexts, and it seems to be working fine in the source version.

    The current master does not build Sinon in a way that works with RequireJS.

    Steps to reproduce https://gist.github.com/mroderick/82fcb7caa43aced684c8

    Some of this was discussed in #553

    @neonstalwart @cjohansen @mantoni I think this is all that is blocking us from doing a new release and drawing a line in the sand. I am too tired to wrap my head around this, if any of you could have a look that would be great.

    AMD 1.x 
    opened by mroderick 36
  • fakeServer is broken with .respond(500) on 1.17.4

    fakeServer is broken with .respond(500) on 1.17.4

    Hi guys,

    I'm using karma-sinon and it's always installing Sinon's latest version by default. It seems that the version 1.17.4 broke this for me:

    this.server.requests[0].respond(500, { 'Content-Type' : 'application/json' }, JSON.stringify({}));

    It won't call the error handler on my Ajax call. For some reason, I can't even find the tag for this version here on Github, to help debug the problem. As a workaround, I've downgraded to 1.17.3 and ran shrinkwrap on my project to be safe.

    • Sinon version : 1.17.4
    • Environment : OSX
    • Other libraries you are using: karma-sinon

    What did you expect to happen? Ajax error to be triggered.

    What actually happens I won't trigger my Ajax error handler.

    How to reproduce

    this.server = sinon.fakeServer.create();
    this.server.requests[0].respond(500, { 'Content-Type' : 'application/json' }, JSON.stringify({}));
    
    Difficulty: Tough Help wanted Needs investigation 
    opened by gil 35
  • Use event loaded instead of error event for code like 403, 500, etc.

    Use event loaded instead of error event for code like 403, 500, etc.

    Purpose (TL;DR) - mandatory

    Codes like 403 and 500 are loaded events not error events.

    Background (Problem in detail) - optional

    Axios.js would not reject a promise for 403 error codes.

    Solution - optional

    Change to use loaded event instead of error event.

    How to verify - mandatory

    1. Check out this branch (see github instructions below)
    2. npm install
    3. tbd
    opened by vietnogi 35
  • Sinon 2.0

    Sinon 2.0

    Making this a pull request that can be used to track progress and dependencies.

    • [x] Build with browserify
    • [x] Run browserified bundle in browsers
    • [ ] Extract fake server
    • [ ] Fix deferred tests
    • [ ] Run CI tests against both source and built version(s)
    • [x] Lint
    • [ ] Figure out a solution for overridable sinon.log
    • [ ] Figure out a solution for overridable sinon.format
    • [ ] Figure out an alternative for sinon.config
    • [ ] Figure which parts of the public API no longer needs to be public (extend, etc)
    • [ ] Figure out which parts to extract as optional add-ons (perhaps assert, test)
    • [ ] Use this as little as possible
    • [ ] Get rid of the sinon.spy() / sinon.spy.create() duality. We don't need sinon.spy.create and the like
    • [ ] Do we still want to support mocks? Are people using mocks?
    • [ ] Clean up code organization: stream-line file names, flatten directory structure
    • [x] Upgrade Buster to a more recent version
    • [ ] Include https://github.com/mroderick/sinon-555 as an automated test somehow
    • [ ] Stubbing an object should not execute getters (in supported browsers)
    • [ ] Stubbing an object property should fail if it is a getter (in supported browsers)
    • [ ] Make fake XHR/server load on Node - remove the checks
    opened by cjohansen 35
  • Sinon.JS homepage design

    Sinon.JS homepage design

    The new Sinon.JS homepage is up 🎉 and it needs help! @mroderick invested a significant amount of time to make a new Jekyll page that is now hosted on GitHub.

    We would ❤️ some help with the design of the page. We'd like to add the content from the README.md to show who is sponsoring the project and link to the Sinon.JS open collective page.

    If you have suggestions or would like to volunteer, please get in touch here.

    Documentation Help wanted 
    opened by mantoni 34
  • Resolving native ES6 promises doesn't trigger callbacks when using fake timers

    Resolving native ES6 promises doesn't trigger callbacks when using fake timers

    In the following test, I expected the callback for the resolved promise to be invoked while inside the test. Apparently, native promises doesn't invoke callbacks synchronously, but schedules them to be called in a manner similar to setTimeout(callback, 0). However, it doesn't actually use setTimeout, so sinon's implementation of fake timers doesn't trigger the callback when calling tick().

    describe 'Promise', ->
      beforeEach ->
        @clock = sinon.useFakeTimers()
      afterEach ->
        @clock.restore()
        console.log 'teardown'
    
      it "should invoke callback", ->
        p = new Promise (resolve, reject) ->
          console.log 'resolving'
          resolve(42)
          console.log 'resolved'
        p.then ->
          console.log 'callback'
        @clock.tick()
        console.log "test finished"
    

    I expect this output:

    resolving
    resolved
    callback
    test finished
    teardown
    

    Instead I get this:

    resolving
    resolved
    test finished
    teardown
    callback
    

    The callback is invoked after the test is finished, so assertions based on what happens inside the callback fail.

    It makes no difference whether the promise is resolved before or after calling then().

    opened by ropez 34
  • Sinon 2.0 Release

    Sinon 2.0 Release

    What do we want to achieve in preparation for releasing a 2.0 release candidate of Sinon?

    @mantoni @fatso83 @cjohansen Here are a handful of proposed tasks; please edit this Issue, or comment below so we can get a list of tasks together and get 2.0 shipped :rocket:

    CommonJS Migrations

    • [x] Migrate sinon.spy #920
    • [x] Migrate sinon.stub #932
    • [x] Migrate sinon.mock #933
    • [x] Migrate fake_server and friends (Bulk of work done in #934, useFakeXMLHttpRequest still referenced, see #1118)
    • [x] Migrate sinon.sandbox (Bulk of work done in #936) #1088
    • [x] Migrate sinon.format (Tightly coupled in tests) #967
    • [x] Migrate sinon.collection #1084

    Test Suite CommonJS Migrations

    • [x] Migrate assert suite #1078
    • [x] Migrate call suite #1079
    • [x] Migrate collection suite #1084
    • [x] Migrate extend suite #1085
    • [x] Migrate match suite #1086
    • [x] Migrate mock suite #1087
    • [x] Migrate sandbox suite #1088
    • [x] Migrate spy suite #1001
    • [x] Migrate stub suite #1001
    • [x] Migrate typeOf suite #1085
    • [x] Migrate util/core suites #998, #1081
    • [x] Migrate util/event suite #1115
    • [x] Migrate util/fake-timers suite #1116
    • [x] Migrate util/fake-server suite #1118
    • [x] Migrate util/fake-server-with-clock suite #1118
    • [x] Migrate util/fake-xdomain-request suite
    • [x] Migrate util/fake-xml-http-request suite #1125

    Cleanup Tasks

    • [x] Break down test/sinon-test.js suite #968
    • [x] Remove sinon.config usage (Decision: #936. Removed entirely in #973)
    • [x] Remove sinon.logError and sinon.log [#972]
    • [x] Use CommonJS imports in tests (No more sinon global access, allows us to remove internal helpers from the public API) #996
    • [x] Document API changes from 1.17 -> 2.0 and provide upgrade advice. #1090

    Public API Changes

    tasks with a ? require clarification from maintainers

    • [x] Extract sinon.test and sinon.testCase into their own NPM module (sinon-test) sinonjs/sinon-test#1 and #973
    • [x] Deprecate use of internal core utils (see #1090)
    • [x] Internalise sinon.extend (General utility not related to Sinon) #1235
    • [x] Internalise sinon.typeOf (General utility not related to Sinon) #1235
    • [x] Remove Legacy IE support / workarounds?
    • [x] Refactor util/fake_server.js so as not to use sinon global

    Outside of Scope

    • Extract sinon.mock into its own module (sinon-mock) (Decision: #745). Not removed until 3.0

    New documentation site

    • [ ] Create and publish a new documentation site, see #1220 for details on remaining work.
    Help wanted 
    opened by jonnyreeves 33
  • Errors with .stub() and .spy() caused by getters/setters

    Errors with .stub() and .spy() caused by getters/setters

    • Sinon version : 4.5.0
    • Environment : ???
    • Example URL : https://github.com/lavelle/sinon-stub-error
    • Other libraries you are using: Webpack

    What did you expect to happen?

    At @thumbtack we are in the process of upgrading our build to Webpack 4. As part of this some of our unit tests started failing. We tracked it down to the cases where we are using Sinon's .spy and .stub functionality on modules that are exported using a non-default ES6 export of the form export function foo. Digging in, it looks like under the hood Webpack creates getters and setters for these exports for its new implementation of Harmony modules. This changed from version 3 to version 4.

    We were also able to reproduce this independent of Webpack by attempting to stub a plain object that has a getter or setter.

    What actually happens

    When using .stub, the stubbing works, but a later call to .restore does not, and the assertion fails.

    When using .spy, the following error is thrown: TypeError: Attempted to wrap undefined property foo as function. For some reason Sinon thinks a property is undefined when it also exists as a getter.

    How to reproduce

    I created a repo that has a minimal reproduction of both the stub and spy issues, with the latest versions of Webpack and Sinon. It also has a base case that shows that this issue does not occur in objects that are not imported this way and therefore don't use setters.

    You can clone the repo here: https://github.com/lavelle/sinon-stub-error

    Run yarn install and then run

    • yarn pass to see the base case
    • yarn fail to see the failing stub case
    • yarn spy to see the failing spy case

    Thanks in advance! We're happy to submit a PR to address this if you can point us in the right direction.

    cc @bawjensen @dcapo

    Property accessors 
    opened by lavelle 32
  • Idea for future milestone(s)

    Idea for future milestone(s)

    Background

    sinon.stub / sandbox.stub has become the kitchen sink of configurable behaviour with issues that are often difficult to find and fix without regressions.

    I think that the root cause of the difficulties is that it stub has far too many responsibilities.

    Further, stub also has problematic usage caused by the fact that behaviour is set after it has been created, and can be redefined many times over.

    var myStub;
    
    beforeEach(function(){
        myStub = sinon.stub().resolves('apple pie :)');
    });
    
    // several hundred lines of tests later
    myStub = sinon.stub().rejects('no more pie :(');
    
    // several hundred lines of tests later
    // what behaviour does myStub currently have? Can you tell without 
    // reading the entire file?
    // can you safely change the behaviour without affecting tests further 
    // down in the file?
    

    And then there are the more confusing scenarios

    var myStub = sinon.stub()
                    .withArgs(42)
                    .onThirdCall()
                    .resolves('apple pie')
                    .rejects('no more pie')
    

    What does that even do?

    Instead of continuing to add more responsibilities to stub, I propose that instead we introduce new members to sinon, which are much narrower in scope.

    The most important I can think of would be an immutable stand in for a function.

    We can then later figure out what we're going to do about properties (as a separate, new, single responsibility member).

    sinon.fake

    A fake (the return value of calling sinon.fake) is a pure and immutable Function. It does one thing, and one thing only. It has the same behaviour on each and every call. Unlike stub, its behaviour cannot be redefined. If you need different behaviour, make a new fake.

    Single responsibility

    A fake can have one of these responsibilities

    • resolve a Promise to a value
    • reject a Promise to an Error
    • return a value
    • throw an Error
    • yield value(s) to a callback

    If you want/need side effects, and you still want the spy interface, then either use the real function, use a stub or make a custom function

    sinon.replace(myObject, myMethod, sandbox.spy(function(args) {
        someFunctionWithSideEffects(args);
    });
    

    Throws errors generously

    Will be generous with throwing errors when user tries to create/use them in unsupported ways.

    // will throw TypeError when `config` argument has more than one property
    const fake = sinon.fake({
        resolves: true, 
        returns: true
    });
    

    Uses the spy API

    Except for .withArgs, as that violates immutability

    Usage ideas

    // will return a Promise that resolves to 'apple pie'
    var fake = sinon.fake({resolves: 'apple pie'})
    
    // will return a Promise that rejects with the provided Error, or 
    // creates a generic Error using the input as message
    var fake = sinon.fake({rejects: new TypeError('no more pie')});
    var fake = sinon.fake({rejects: 'no more pie'});
    
    // returns the value passed
    var fake = sinon.fake({returns: 'apple pie'});
    
    // throws the provided Error, or creates a generic Error using the 
    // input as message
    var fake = sinon.fake({throws: new RangeError('no more pie')});
    var fake = sinon.fake({throws: 'no more pie'});
    
    // replace a method with a fake
    var fake = sinon.replace(myObject, 'methodName', sandbox.fake({
        returns: 'apple pie'
    }))
    // .. or use the helper method, which will use `sandbox.replace` and `
    // sinon.fake`
    var fake = sinon.setFake(global, 'methodName', {
        returns: 'apple pie'
    });
    
    // create an async fake
    var asyncFake = sinon.asyncFake({
        returns: 'apple pie'
    });
    

    Synonyms

    I don't know if fake is the best noun to use here, but I think we should try to stick to the convention of using nouns, and not stray into adjectives or verbs.

    Proposed API changes

    Use a default sandbox

    This is something I've been considering for awhile, why don't we make a default sandbox? If people need separate sandboxes, they can still create them.

    We should create a default sandbox that is used for all methods that are exposed via sinon.*. This means that sinon.stub will become the same as sandbox.stub, which will remove the limitation of being able to stub properties using sinon.stub.

    sandbox.replace

    Create sandbox.replace and use that for all operations that replace anything anywhere. Expose this as sinon.replace and use the default sandbox when used this way.

    This should probably have some serious input validation, so it'll only replace functions with functions, accessors with accessors, etc.

    Feature Request Improvement Needs investigation pinned 
    opened by mroderick 31
  • fix: assertion log limit

    fix: assertion log limit

    Purpose (TL;DR) - mandatory

    Allow for a log limit setting on the assertion object, that when true, will truncate the error.message that is returned via a failing assertion. The limit for the log message will be set to a default if none was provided

    https://github.com/sinonjs/sinon/issues/2484

    Background (Problem in detail) - optional

    When a stubbed method has a large property on it, it is logged in the failing assertion causing runoff in the terminal and making it hard to see what assertion actually failed.

    By allowing for a log limitation setting and a default log limit, error logs can be truncated.

    How to verify - mandatory

    1. use this app and point the sinon instance to this version
    2. see the logs are reduced when the setting is on

    Checklist for author

    • [x] npm run lint passes
    • [x] References to standard library functions are cached.
    opened by sgoossens 0
  • Enable and Set Assertion Logging Limits

    Enable and Set Assertion Logging Limits

    when sinon.assert fails for a stubbed method that had potentially a large amount of data on it, it logs the entirety of the stub each time which can cause runoff on the terminal see here making it very hard to debug. It would be nice to be able to toggle on a log threshold limit such that we can control the amount that is logged out when an assertion fails.

    opened by sgoossens 0
  • Bump simple-git from 3.14.1 to 3.15.1

    Bump simple-git from 3.14.1 to 3.15.1

    Bumps simple-git from 3.14.1 to 3.15.1.

    Release notes

    Sourced from simple-git's releases.

    [email protected]

    Patch Changes

    • de570ac: Resolves an issue whereby non-strings can be passed into the config switch detector.

    [email protected]

    Minor Changes

    • 7746480: Disables the use of inline configuration arguments to prevent unitentionally allowing non-standard remote protocols without explicitly opting in to this practice with the new allowUnsafeProtocolOverride property having been enabled.

    Patch Changes

    • 7746480: - Upgrade repo dependencies - lerna and jest
      • Include node@19 in the test matrix
    Changelog

    Sourced from simple-git's changelog.

    3.15.1

    Patch Changes

    • de570ac: Resolves an issue whereby non-strings can be passed into the config switch detector.

    3.15.0

    Minor Changes

    • 7746480: Disables the use of inline configuration arguments to prevent unitentionally allowing non-standard remote protocols without explicitly opting in to this practice with the new allowUnsafeProtocolOverride property having been enabled.

    Patch Changes

    • 7746480: - Upgrade repo dependencies - lerna and jest
      • Include node@19 in the test matrix
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the Security Alerts page.
    dependencies javascript 
    opened by dependabot[bot] 1
  • AssertError: async function myfunct() ... is not stubbed

    AssertError: async function myfunct() ... is not stubbed

    I'm getting "async function" ... "is not stubbed" errors on sinon test code that used to work fine.

    We have a module that has an exported function, i.e. mymodule.js has

    export async function myFunction() {
    ...
    }
    

    The test in question stubs a module-level exported function...

    sinon.stub(myModule, 'myFunction');
    

    then calls it, and then we do

    sinon.assert.calledOnce(myModule.myFunction)
    

    and we get the error above.

    It used to work, but we've migrated our project from yarn to pnpm and some sinon-related packages drifted, but it's hard to figure out what's wrong.

    Any idea why a module-level exported function which is stubbed, would then give "is not stubbed" shortly after?

    opened by GeoffreyPlitt 1
  • Using `restore` after `createStubInstance` creates frankenstein objects

    Using `restore` after `createStubInstance` creates frankenstein objects

    Describe the bug Restoring stubs created by createStubInstance creates frankenstein objects that have the original prototype-chain of the object passed in without the object having been properly created through the constructor.

    To Reproduce Here is a jsfiddle demonstrating the following code

    class TestObject {
      constructor() {
        this.constructorDidRun = true;
      }
      
      doSomething() {
        if (!this.constructorDidRun) {
          throw new Error("I am Frankenstein's monster!!")
        }
      }
    }
    
    const sandbox = sinon.createSandbox();
    const stubInstance = sandbox.createStubInstance(TestObject);
    
    stubInstance.doSomething(); // does nothing, as expected
    
    sandbox.restore();
    
    stubInstance.doSomething(); // uh-oh!
    

    Expected behavior I'm not totally certain, but perhaps nothing? For us, the use-case of createStubInstance is to create drop-in objects that simulate the provided object's interface, but without ever touching its implementation. We use them in unit-testing to validate interactions. I'm not sure the use-case where you'd want a partial object that has not had its constructor run, so I cannot imagine this is intended behavior (and even in that case, I would expect to expose that behavior using stub.callThrough(), rather than by restoring the sandbox).

    Context

    • Library version: 14.0.2
    • Environment: Node/browser
    • Example URL: https://jsfiddle.net/dpraul/4atk8jdv/2

    Additional Context This behavior came to our attention as we're updating our application from Angular 13 to Angular 14. Angular 14 updates the default TestBed behavior to tear down the test module after each test. While this is arguably a good addition as it provides a cleaner testing environment for each test, it has brought these frankenstein objects to our attention.

    Since a sandox is created and restored inside of a test-suite, but the TestBed teardown occurs after the suite, the TestBed still holds references to these partial objects. The TestBed cleanup triggers any OnDestroy methods on the objects, which may now have implementations associated with them.

    NOTE: This particular issue may be better-solved a multitude of ways (perhaps by introducing the TestBed teardown into the afterEach of the suite and prior to restoring the sandbox). Nonetheless, it seems like an issue that the implementations of these stubbed objects are being reintroduced back to the test suite, even after the suite has completed.

    Here is an example of this issue in our application
    import * as sinon from "sinon";
    import { of } from "rxjs";
    import { Injectable, OnDestroy } from "@angular/core";
    import { TestBed } from "@angular/core/testing";
    
    @Injectable({ providedIn: "root" })
    class Dependency implements OnDestroy {
      private subscription = of(null).subscribe();
    
      ngOnDestroy() {
        // It's common to use the OnDestroy lifecycle hook to clean-up any RxJS subscriptions.
        // The sandbox is restored in afterEach, which re-introduces this implementation,
        // but since the constructor has never been called this.subscription will be undefined, so a TypeError is thrown
        this.subscription.unsubscribe();
      }
    }
    
    @Injectable({ providedIn: "root" })
    class ServiceUnderTest {
      constructor(private dependency: Dependency) {}
    
      doSomething(): boolean {
        return true;
      }
    }
    
    describe("Test Suite", () => {
      let service: ServiceUnderTest;
      let sandbox: sinon.SinonSandbox;
      let mockDependency: sinon.SinonStubbedInstance<Dependency>;
    
      beforeEach(() => {
        sandbox = sinon.createSandbox();
        mockDependency = sandbox.createStubInstance(Dependency);
    
        TestBed.configureTestingModule({
          providers: [
            ServiceUnderTest,
            { provide: Dependency, useValue: mockDependency }
          ]
        });
        service = TestBed.inject(ServiceUnderTest);
      });
    
      afterEach(() => {
        sandbox.restore();
      });
    
      it("should do something", () => {
        expect(service.doSomething()).toBe(true);
      });
    });
    
    opened by dpraul 0
  • sandbox.restore() doesn't works between two 'describe' (mocha Suite)

    sandbox.restore() doesn't works between two 'describe' (mocha Suite)

    Hello to all, I have a problem to use the sandbox between two 'describe': basically the restore function seems not to restore the original functions, stubbed using the sandbox. The stubbed version still remains across the two 'describe' I also tried to clear the modules 'my-library' and 'sinon' from the 'require' cache, without success

    Someone faced the same problem ?

    import chai, { expect } from 'chai';
    import chaiHttp from 'chai-http';
    import { AuthHelper } from 'my-library';
    const sinon = require('sinon');
    
    chai.use(chaiHttp);
    
    describe('suite1', () => {
      let serverApp: any;
      let sandbox: any;
    
      afterEach(() => {
        sandbox.restore();
      });
    
      before(()=>{
          sandbox = sinon.createSandbox();
      });
    
      beforeEach(() => {
        sandbox.stub(AuthHelper, 'authExpressMiddleware').callsFake((options: any) => (req: any, res: any, next: any) => {
    	  console.log("Stubbed authExpressMiddleware");
          return next();
        });
        serverApp = require('myExpressApp');
      });
    
      it('test1', (done) => {
    
        chai.request(serverApp)
          .get(`my-action`)
          .end((err, res) => {
            expect(res.status).to.equal(200);
            done();
          });
      });
    });
    
    describe('suite2', () => {
      let serverApp: any;
      let sandbox: any;
    
      afterEach(() => {
        sandbox.restore();
      });
      
       before(()=>{
          sandbox = sinon.createSandbox();
      });
    
      beforeEach(() => {
        // PROBLEM: the test should pass (return 401) because I don't stub the auth middleware, 
       // but the test fails because the previous stub is called (I see the message "Stubbed authExpressMiddleware" also in the suite2)
    
        serverApp = require('myExpressApp');
      });
    
      it('test1', (done) => {
        chai
          .request(serverApp)
          .get(`my-action`)
          .end((request, res) => {
            expect(res.status).to.equal(401);
            done();
          });
      });
    });
    
    
    opened by lunard-gruber-logistics 5
Releases(v4.2.2)
  • v4.2.2(Jan 26, 2018)

  • v4.2.1(Jan 23, 2018)

  • v4.2.0(Jan 23, 2018)

  • v4.1.6(Jan 23, 2018)

  • v4.1.5(Jan 13, 2018)

  • v4.1.4(Jan 8, 2018)

  • v3.2.0(Aug 10, 2017)

  • v3.1.0(Aug 8, 2017)

    • Add factory functions for sandbox and fake server (#1515)
    • Add support for passing a function to stub.throws(...). (#1511)
    • Lots of documentation updates
    • Fix regression on sandbox.stub(obj,protoMethod) (#1512)
    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Aug 3, 2017)

    • Remove deprecated exports see migration guide
    • Fix #1432: add details around expectations.withArgs behavior to docs (#1501)
    • Fix #1487: incorrect withArgs().returnValue
    • add format.setFormatter
    • Upgrade lolex to 2.1.2
    • Extract fakeXhr, fakeServer and fakeServerWithClock into own module nise and re-import it to keep api the same
    Source code(tar.gz)
    Source code(zip)
  • v2.3.8(Jul 13, 2017)

  • v2.3.7(Jul 10, 2017)

  • v2.3.6(Jul 10, 2017)

  • v2.3.5(Jun 20, 2017)

  • v2.3.4(Jun 10, 2017)

  • v2.3.3(Jun 10, 2017)

  • v2.3.2(May 26, 2017)

    • Fix failing sandbox.resetBehavior() (#1428)
    • Fix restoring getters/setters/values for previously unexisting props (#1419)
    • Called in order takes callCount into account. Closes #1398.
    Source code(tar.gz)
    Source code(zip)
  • v2.3.1(May 23, 2017)

  • v2.3.0(May 22, 2017)

    • Allow stubbing of accessors with and without sandbox (#1416)
    • add throwsArg(index) to stubs (#1319)
    • Fix: forEach() requires 'this' argument (#1356)
    • Only reset history when calling resetHistory()
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jul 25, 2017)

    This is the big 2.0 release with lots of breaking changes. We have created a migration guide on the Sinon homepage you are advised to follow.

    Changes since pre6

    • Add restore method for stubbed property descriptors
    • Allow stubbing getters and setters for function properties
    • Add getters/setters stub behaviors
    • Refactor xhr and xhr.upload to use the same EventTargetHandler
    • Remove SSL part of base url
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-pre.4(Nov 10, 2016)

    Changes in this release, compared to v2.0.0-pre.3

    • #1061 add configurable unsafe header checks
    • #1173 Expose readyState constants on XHR instances
    • #1175 Fire .onprogress event handler in fake XHR
    • #1176 Implement XHR.overrideMimeType
    • #1183 Use last defined withArgs match when multiple conditions are met

    Full comparison

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-pre.2(Jul 27, 2016)

    • CJSify remaining tests
    • Expose sinon.assert on sandbox instances. (#1076)
    • Add resetBehavior and resetHistory to sandbox API (#1072)
    • Add sandbox.reset() docs
    • Allow xhr.respond(0) to simulate a network failure and call onerror
    • Use event loaded instead of error event for code like 403, 500, etc.
    • Fix invalid markdown in fake-timers.ms (#1054)
    • Do not invoke getters in walk (#1059)
    • ReactNative compatibility. Allow sinon fakeServer to run in React Native (#1052)
    • Fix onerror event triggering for fake xhr requests (#1041)
    • Allow sinon.calledInOrder to be called either with an array of spies or multiple spies as parameters. Add explicit test cases for sinon.calledInOrder
    • Document faking of setImmediate and clearImmediate
    • Add support for es6 Symbol to wrapMethod, match.same, yieldTo, match methods.
    • Transition to Mocha and ESLint for tests
    • Feature detect proto to exclude a timer test in IE 10
    • Migrate Packaged Tests to use a Browserified Build.
    • Improve Blob support detection logics
    • Remove sinon.test() and sinon.testCase (now in sinon-test module.)
    • Remove sinon.log and sinon.logError
    • Fix 648: test for this.proxy before trying toString on it
    • use the correct sinon.deepEqual to test sinon matcher
    • Get rid of eval in sinon spy
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-pre(Jul 27, 2016)

    • Fix #875 Proper support UTF8 payloads
    • CommonJS-ified some of the things
    • updated readyStateChange to align to the w3c spec (somewhat)
    • added some additional progress event verification
    • added a test to ensure load is not fired before abort
    • added test to ensure event ordering
    • allow progress events with loaded/total values of 0
    • Fix #867: Walk properties only once
    • Removed unnecessary module wrappers and double test run in NodeJS.
    • null-check the object passed to sinon.stub
    • implemented stub#resetHistory method - fixes #863
    • Fix #851: Do not attempt to re-stub constructors
    • Fix #847: Ensure walk invokes accessors directly on target
    • stub.reset also resets behavior
    Source code(tar.gz)
    Source code(zip)
Owner
Sinon.JS
Standalone test spies, stubs and mocks for JavaScript.
Sinon.JS
🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
Minimalistic BDD-style assertions for Node.JS and the browser.

Expect Minimalistic BDD assertion toolkit based on should.js expect(window.r).to.be(undefined); expect({ a: 'b' }).to.eql({ a: 'b' }) expect(5).to.be.

Automattic 2.1k Jan 4, 2023
Some stuff for testing, such as mocks, object mother, etc.

Built with ❤︎ by maintainers Testing Some stuff for testing, such as mocks, object mother, etc. Installation yarn add git+https://github.com/turnly/te

Turnly 6 Jul 21, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Jester is a test-generation tool to create integration test code.

Code Generator for Integration Tests Introduction Welcome to Jester: An easy-to-use web application that helps you create and implement integration te

OSLabs Beta 54 Dec 12, 2022
In this project I write the test for several functions and used the TDD with Jest and JavaScript.

JavaScript-Testing-with-Jest npm init -y npm install --save-dev jest Once installed, you should see it in already created Json file Change Jest Script

Ben Kiboma Omayio 2 Jun 11, 2022
Spectacular Test Runner for JavaScript

Karma A simple tool that allows you to execute JavaScript code in multiple real browsers. The main purpose of Karma is to make your test-driven develo

Karma 11.8k Dec 27, 2022
☕️ simple, flexible, fun javascript test framework for node.js & the browser

☕️ Simple, flexible, fun JavaScript test framework for Node.js & The Browser ☕️ Links Documentation Release Notes / History / Changes Code of Conduct

Mocha 21.8k Dec 30, 2022
A JavaScript / WebAssembly library for generating regular expressions from user-provided test cases

1. What does this library do? grex is a library that is meant to simplify the often complicated and tedious task of creating regular expressions. It d

Peter M. Stahl 164 Dec 30, 2022
A leetcode workspace template with test case runner for JavaScript/TypeScript programmers.

leetcode-typescript-workspace English | 简体中文 A vscode workspace template with test case runner script for JavaScript/TypeScript programmers using exte

null 10 Dec 13, 2022
A simple tap test runner that can be used by any javascript interpreter.

just-tap A simple tap test runner that can be used in any client/server javascript app. Installation npm install --save-dev just-tap Usage import cre

Mark Wylde 58 Nov 7, 2022
Clock and task scheduler for node.js applications, providing extensive control of time and callback scheduling in prod and test code

#zeit A node.js clock and scheduler, intended to take place of the global V8 object for manipulation of time and task scheduling which would be handle

David Denton 12 Dec 21, 2021
Clock and task scheduler for node.js applications, providing extensive control of time and callback scheduling in prod and test code

#zeit A node.js clock and scheduler, intended to take place of the global V8 object for manipulation of time and task scheduling which would be handle

David Denton 12 Dec 21, 2021
This repository contains a basic example on how to set up and run test automation jobs with CircleCI and report results to Testmo.

CircleCI test automation example This repository contains a basic example on how to set up and run test automation jobs with CircleCI and report resul

Testmo 2 Dec 23, 2021
Fast and robust triangle-triangle intersection test with high precision for cross and coplanar triangles based on the algorithm by Devillers & Guigue.

fast-triangle-triangle-intersection Fast and robust triangle-triangle intersection test with high precision for cross and coplanar triangles based on

Technology and knowledge for interaction 10 Nov 15, 2022
A low-feature, dependency-free and performant test runner inspired by Rust and Deno

minitest A low-feature, dependency-free and performant test runner inspired by Rust and Deno Simplicity: Use the mt test runner with the test function

Sondre Aasemoen 4 Nov 12, 2022
Three.js boilerplate project configured with typescript, webpack and css/style loader, HTTPS local server, and a sample test codes !!

three.js-boilerplate Welcome, this is a three.js boilerplate project where you can clone it and start to work !!! Installed and Configured Items: Type

pravin poudel 4 Jul 6, 2022
Starting a new JS app? Build, test and run advanced apps with kyt 🔥

kyt Every sizable JavaScript web app needs a common foundation: a setup to build, run, test and lint your code. kyt is a toolkit that encapsulates and

The New York Times 1.9k Dec 26, 2022