How to use sinon - 10 common examples

To help you get started, we’ve selected a few sinon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mixpanel / mixpanel-js / tests / unit / autotrack-utils.js View on Github external
it(`shouldn't inadvertently replace DOM nodes`, function() {
      // setup
      el.replace = sinon.spy();

      // test
      parent1.name = el;
      shouldTrackElement(parent1); // previously this would cause el.replace to be called
      expect(el.replace.called).to.equal(false);
      parent1.name = undefined;

      parent1.id = el;
      shouldTrackElement(parent2); // previously this would cause el.replace to be called
      expect(el.replace.called).to.equal(false);
      parent1.id = undefined;

      parent1.type = el;
      shouldTrackElement(parent2); // previously this would cause el.replace to be called
      expect(el.replace.called).to.equal(false);
      parent1.type = undefined;
github abecms / abecms / tests / unit / cms / operations / create.js View on Github external
it('cmsOperations.create()', function(done) {
    // stub
    var s = sinon.sandbox.create();
    s.stub(abeExtend.hooks.instance, 'trigger', function (str, obj, body, json) {
      return str, obj;
    }.bind(this));
    s.stub(coreUtils.slug, 'clean', function (p) { return p; }.bind(this));
    s.stub(Manager.instance, 'postExist', function (p) { return false; }.bind(this));
    s.stub(cmsData.metas, 'create', function (json, template, postUrl) { return json; }.bind(this));
    s.stub(cmsTemplates.template, 'getTemplate', function () { return this.fixture.htmlArticle; }.bind(this));
    s.stub(cmsData.values, 'removeDuplicate', function (templateText, json) { return json; }.bind(this));
    s.stub(cmsOperations.post, 'draft', function () {
      return Promise.resolve({json: JSON.parse(JSON.stringify(this.fixture.jsonArticle))})
    }.bind(this));

    cmsOperations.create('article', '/article-2.html', JSON.parse(JSON.stringify(this.fixture.jsonArticle)))
      .then(function(resSave) {
        var json = path.join(Manager.instance.pathData, resSave.abe_meta.latest.abeUrl.replace('.html', '.json'))
github accordproject / concerto / test / serializer / jsonpopulator.js View on Github external
it('should create a new relationship from an array of objects if permitted', () => {
            jsonPopulator = new JSONPopulator(true); // true to enable acceptResourcesForRelationships
            let options = {
                jsonStack: new TypedStack([{
                    $class: 'org.acme.MyAsset1',
                    assetId: 'asset1'
                }, {
                    $class: 'org.acme.MyAsset1',
                    assetId: 'asset2'
                }]),
                resourceStack: new TypedStack({}),
                factory: mockFactory,
                modelManager: modelManager
            };
            let mockResource1 = sinon.createStubInstance(Resource);
            mockFactory.newResource.withArgs('org.acme', 'MyAsset1', 'asset1').returns(mockResource1);
            let mockResource2 = sinon.createStubInstance(Resource);
            mockFactory.newResource.withArgs('org.acme', 'MyAsset1', 'asset2').returns(mockResource2);
            let subResources = jsonPopulator.visitRelationshipDeclaration(relationshipDeclaration2, options);
            subResources.should.have.length.of(2);
            subResources[0].should.be.an.instanceOf(Resource);
            subResources[1].should.be.an.instanceOf(Resource);
        });
github aws / aws-iot-device-sdk-js / test / thing-unit-tests.js View on Github external
it("should generate a token", function() {
          // Reinit mockMQTTClientObject
          mockMQTTClientObject.reInitCommandCalled();
          mockMQTTClientObject.resetPublishedMessage();
          // Faking timer
          var clock = sinon.useFakeTimers();
          // Faking callback
          var fakeCallback = sinon.spy();
          // Init thingShadowClient
          var thingShadows = thingShadow( {
            keyPath:'test/data/private.pem.key',
            certPath:'test/data/certificate.pem.crt',
            caPath:'test/data/root-CA.crt',
            clientId:'dummy-client-1',
            host:'XXXX.iot.us-east-1.amazonaws.com'
          }, {  
            operationTimeout:1000 // Set operation timeout to be 1 sec
          } );
          // Register callback
          thingShadows.on('timeout', fakeCallback);
          // Register a thing
          thingShadows.register('testShadow3');
github jaegertracing / jaeger-client-node / test / samplers / guaranteed_throughput_sampler.js View on Github external
it('should provide minimum throughput', () => {
    let initialDate = new Date(2011, 9, 1).getTime();
    let clock = sinon.useFakeTimers(initialDate);
    let sampler = new GuaranteedThroughputSampler(2, 0);
    clock = sinon.useFakeTimers(initialDate + 20000);

    let expectedTags = { 'sampler.type': 'lowerbound', 'sampler.param': 0 };
    [true, true, false].forEach(expectedDecision => {
      let actualTags = {};
      let decision = sampler.isSampled('testOperationName', actualTags);
      // We asked for 2 traces per second and 0% probability for the rest.
      // Since the test runs under one second, we expect 2 successful samples
      // and one unsuccessful.
      if (expectedDecision) {
        assert.isTrue(decision, 'must sample');
        assert.deepEqual(expectedTags, actualTags);
      } else {
        assert.isFalse(decision, 'must not sample');
        assert.deepEqual({}, actualTags);
github jaegertracing / jaeger-client-node / test / rate_limiter.js View on Github external
it('update balance', () => {
    let initialDate = new Date(2011, 9, 1).getTime();
    let clock = sinon.useFakeTimers(initialDate);
    let limiter = new RateLimiter(0.1, 1);
    assert.equal(
      true,
      limiter._balance <= 1 && limiter._balance >= 0,
      'balance should be initialized to a random value between [0:1]'
    );
    limiter._balance = 1.0;
    assert.equal(limiter.checkCredit(1), true, 'expected checkCredit to be true');

    limiter.update(0.1, 3);
    clock.restore();
    // move time 20s forward, enough to accumulate credits for 2 messages
    clock = sinon.useFakeTimers(initialDate + 20000);
    assert.equal(limiter.checkCredit(1), true, 'expected checkCredit to be true');
    assert.equal(limiter.checkCredit(1), true, 'expected checkCredit to be true');
    assert.equal(limiter.checkCredit(1), false, 'expected checkCredit to be false');

    // move time 30s forward, enough to accumulate credits for another message (should have
    // enough credits for 3 at this point)
    clock = sinon.useFakeTimers(initialDate + 50000);
    assert.equal(limiter.checkCredit(1), true, 'expected checkCredit to be true');
    assert.equal(limiter._balance, 2, 'balance should be at 2 after spending 1');

    // move time 5s forward, not enough to accumulate credits for another message
    clock = sinon.useFakeTimers(initialDate + 55000);
    // reduce the maxBalance so the limiter is capped at 1
    limiter.update(0.1, 1);
    assert.equal(limiter._balance, 2.5 / 3.0, 'balance should be proportional to the original range');
    assert.equal(limiter.checkCredit(1), false, 'expected checkCredit to be false');
github apifytech / apify-js / test / actor.js View on Github external
const testMain = async ({ userFunc, exitCode }) => {
    // Mock process.exit() to check exit code and prevent process exit
    const processMock = sinon.mock(process);
    const exitExpectation = processMock
        .expects('exit')
        .withExactArgs(exitCode)
        .once()
        .returns();

    let error = null;

    try {
        await Promise.resolve()
            .then(() => {
                return new Promise((resolve, reject) => {
                    // Invoke main() function, the promise resolves after the user function is run
                    Apify.main(() => {
                        try {
                            // Wait for all tasks in Node.js event loop to finish
github Ariel-Rodriguez / react-amp-template / test / spec / amp / index.js View on Github external
import Validator from '../../../lib/utils/ampvalidator';
import { expect } from 'chai';
import sinon from 'sinon';
import AppStatic from '../../mocks/appStatic';

const sx = sinon.sandbox.create();
let validator;
let AppHTML;

describe('AMP Validation', sinon.test(() => {
  before('setup', (done) => {
    Validator.getInstance().then((instance) => {
      validator = instance;
      // warm up validator
      validator.validateMarkup('', true);
    })
    .then(AppStatic.render)
    .then((html) => {
      AppHTML = html;
      done();
    });
  });

  after(() => {
    sx.restore();
  });
github mheap / trello-cli / test / authenticate.js View on Github external
describe('#loadAuthCache()', sinon.test(function() {
        // We use sinon.stub not this.stub to persist across tests
        config = sinon.stub(config, "get")
        config.withArgs('configPath').returns('/tmp/.missing.trello-cli/');
        config.withArgs('authCache').returns('auth.json');
        logger = sinon.mock(logger)

        it('should parse valid JSON file', sinon.test(function() {
            this.stub(Auth.fs, "readFileSync").returns('{}');
            expect(Auth.loadAuthCache()).to.eql({})
        }));

        it('should create empty auth file if none exists', sinon.test(function() {
            this.stub(Auth.fs, "readFileSync").throws()
            logger.expects("debug").withExactArgs('No auth file found: /tmp/.missing.trello-cli/auth.json')
            logger.expects("debug").withExactArgs('Auth file created')

            var spy = this.spy(Auth, "writeAuthFile")

            Auth.loadAuthCache()

            expect(spy).to.have.been.calledOnce;
        }));
    }));
github segmentstream / digital-data-manager / test / DigitalDataEnricher.spec.js View on Github external
]
        }
      })

      // +2 quantity
      assert.ok(eventsSpy.calledWith(sinon.match({
        name: 'Added Product',
        category: 'Ecommerce',
        product: {
          id: '1'
        },
        quantity: 2
      })))

      // +1 new item
      assert.ok(eventsSpy.calledWith(sinon.match({
        name: 'Added Product',
        category: 'Ecommerce',
        product: {
          id: '2'
        },
        quantity: 1
      })))

      // -3 items
      assert.ok(eventsSpy.calledWith(sinon.match({
        name: 'Removed Product',
        category: 'Ecommerce',
        product: {
          id: '3'
        },
        quantity: 3