sinon#spy TypeScript Examples

The following examples show how to use sinon#spy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.spec.ts    From css-render with MIT License 6 votes vote down vote up
describe('# mount & unmount with id (suite 2)', function () {
  const style = c('.red-block', {
    backgroundColor: 'red'
  })
  beforeEach(() => {
    spy(console, 'error')
  })
  afterEach(() => {
    (console.error as SinonSpy).restore()
    style.unmount()
  })
  it('should mount same element with same id', function () {
    const el = style.mount({
      id: '14141'
    })
    const el2 = style.mount({
      id: '14141'
    })
    expect(el).to.equal(el2)
  })
})
Example #2
Source File: index.spec.ts    From css-render with MIT License 5 votes vote down vote up
describe('# mount with no id', () => {
  let sandbox: HTMLElement
  const style = c('.red-block', {
    backgroundColor: 'red'
  })
  before(() => {
    style.mount()
    sandbox = document.createElement('div')
    document.body.appendChild(sandbox)
  })
  beforeEach(() => {
    spy(console, 'error')
  })
  afterEach(() => {
    (console.error as SinonSpy).restore()
    sandbox.innerHTML = ''
  })
  it('should mount only once', () => {
    expect(document.querySelectorAll('[cssr-id]').length).to.equal(1)
    style.mount()
    expect(document.querySelectorAll('[cssr-id]').length).to.equal(1)
  })
  it('should make element styled', () => {
    sandbox.innerHTML = '<div class="red-block"></div>'
    const backgroundColor = getComputedStyle(
      sandbox.children[0]
    ).backgroundColor
    expect(backgroundColor).to.equal('rgb(255, 0, 0)')
  })
  it('should support props of render', () => {
    sandbox.innerHTML = '<sel1></sel1>'
    const style = c('sel1', ({ props }) => {
      return {
        backgroundColor: props.color
      }
    })
    style.mount({
      props: {
        color: 'red'
      }
    })
    const backgroundColor = getComputedStyle(
      sandbox.children[0]
    ).backgroundColor
    expect(backgroundColor).to.equal('rgb(255, 0, 0)')
  })
  after(() => {
    document.body.removeChild(sandbox)
    style.unmount()
  })
})
Example #3
Source File: index.spec.ts    From css-render with MIT License 5 votes vote down vote up
describe('# mount & unmount with id (suite 1)', () => {
  const style = c('.red-block', {
    backgroundColor: 'red'
  })
  before(() => {
    style.mount({
      id: 'test-id-1'
    })
    style.mount({
      id: 'test-id-2'
    })
    style.mount({
      id: '14138'
    })
    style.mount({
      id: '14139'
    })
  })
  beforeEach(() => {
    spy(console, 'error')
  })
  afterEach(() => {
    (console.error as SinonSpy).restore()
  })
  it('should work in no-count mode', () => {
    expect(exists('jjy')).to.eq(false)
    style.mount({ id: 'jjy' })
    expect(exists('jjy')).to.eq(true)
    expect(document.head.querySelector('[cssr-id="jjy"]')).not.to.eq(null)
    style.unmount({ id: 'jjy' })
    expect(document.head.querySelector('[cssr-id="jjy"]')).to.eq(null)
  })
  it('should mount desired style element on head', () => {
    expect(document.head.querySelector('[cssr-id="test-id-1"]')).not.to.equal(
      null
    )
    expect(document.head.querySelector('[cssr-id="14138"]')).not.to.equal(null)
  })
  it('should do nothing when unmount with an not exist id', () => {
    style.unmount({
      id: 'letitbe'
    })
    expect(style.els.length).to.equal(4)
  })
  it('should unmount the desired style element', () => {
    style.unmount({
      id: 'test-id-1'
    })
    style.unmount({
      id: '14138'
    })
    expect(document.head.querySelector('[cssr-id="test-id-1"]')).to.equal(null)
    expect(document.head.querySelector('[cssr-id="test-id-2"]')).not.to.equal(
      null
    )
    expect(document.head.querySelector('[cssr-id="14138"]')).to.equal(null)
    expect(document.head.querySelector('[cssr-id="14139"]')).not.to.equal(null)
    expect(style.els.length).to.equal(2)
  })
  it('should unmount all related styles elements', () => {
    style.unmount()
    expect(style.els.length).to.equal(0)
  })
  after(() => {
    style.unmount()
  })
})
Example #4
Source File: logger-spec.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
describe("the Language Server Logger", () => {
  let errorSpy;

  beforeEach(() => {
    errorSpy = spy(console, "error");
  });

  afterEach(() => {
    restore();
  });

  it("supports structured JSON logging", async () => {
    getLogger().error("hello world", { a: 1, b: [1, 2, 3] });
    const logEntry = errorSpy.args[0];
    const jsonLogEntry = JSON.parse(logEntry);
    expect(jsonLogEntry).to.have.property("a", 1);
    expect(jsonLogEntry).to.have.deep.property("b", [1, 2, 3]);
  });

  context("log level", () => {
    let orgLevel: LogLevel;

    beforeEach(() => {
      orgLevel = getLogLevel();
    });

    it("supports changing the log level", async () => {
      setLogLevel("fatal");
      getLogger().error(
        "`error` is lower than `fatal` so no logging should happen"
      );
      expect(errorSpy).to.have.not.been.called;
      getLogger().fatal("`fatal` should cause logging to the console");
      expect(errorSpy).to.have.been.called;
    });

    it("does not allow changing to an **unknown** logLevel", async () => {
      // "Verbose" is not a valid log level for the language server
      setLogLevel("Verbose" as "trace");
      const currentLogLevel = getLogLevel();
      expect(currentLogLevel).to.not.equal("Verbose");
      expect(validLoggingLevelValues[currentLogLevel]).to.be.true;
    });

    afterEach(() => {
      setLogLevel(orgLevel);
    });
  });
});
Example #5
Source File: utils.spec.ts    From opentelemetry-ext-js with Apache License 2.0 5 votes vote down vote up
describe('elasticsearch utils', () => {
    const spanMock = {
        recordException: (err) => {},
        setStatus: (obj) => {},
        end: () => {},
        setAttributes: (obj) => {},
    };

    context('defaultDbStatementSerializer', () => {
        it('should serialize', () => {
            const result = Utils.defaultDbStatementSerializer('operationName', { index: 'test' }, {});
            expect(result).to.equal('{"params":{"index":"test"},"options":{}}');
        });
    });

    context('onError', () => {
        it('should record error', () => {
            const recordExceptionStub = stub(spanMock, 'recordException');
            const setStatusStub = stub(spanMock, 'setStatus');
            const endStub = stub(spanMock, 'end');

            const error = new Error('test error');

            // @ts-ignore
            Utils.onError(spanMock, error);

            assert.calledOnce(recordExceptionStub);
            assert.calledWith(recordExceptionStub, error);

            assert.calledOnce(setStatusStub);
            assert.calledWith(setStatusStub, { code: SpanStatusCode.ERROR, message: error.message });

            assert.calledOnce(endStub);

            recordExceptionStub.restore();
            setStatusStub.restore();
            endStub.restore();
        });
    });

    context('onResponse', () => {
        it('should record response without responseHook', () => {
            const setAttributesStub = stub(spanMock, 'setAttributes');
            const setStatusStub = stub(spanMock, 'setStatus');
            const endStub = stub(spanMock, 'end');

            // @ts-ignore
            Utils.onResponse(spanMock, { meta: { connection: { url: 'http://localhost' } } });

            assert.calledOnce(setAttributesStub);
            assert.calledOnce(setStatusStub);
            assert.calledOnce(endStub);
            assert.calledWith(setStatusStub, { code: SpanStatusCode.OK });

            setAttributesStub.restore();
            setStatusStub.restore();
            endStub.restore();
        });

        it('should record response with responseHook', () => {
            const setAttributesStub = stub(spanMock, 'setAttributes');
            const setStatusStub = stub(spanMock, 'setStatus');
            const endStub = stub(spanMock, 'end');

            const responseHook = spy();

            // @ts-ignore
            Utils.onResponse(spanMock, { meta: { connection: { url: 'http://localhost' } } }, responseHook);

            assert.calledOnce(setAttributesStub);
            assert.calledOnce(setStatusStub);
            assert.calledOnce(endStub);
            assert.calledWith(setStatusStub, { code: SpanStatusCode.OK });

            expect(responseHook.called).to.be.true;

            setAttributesStub.restore();
            setStatusStub.restore();
            endStub.restore();
        });
    });

    context('getNetAttributes', () => {
        const url = 'http://localhost:9200';
        const attributes = Utils.getNetAttributes(url);

        it('should get hostname from url', () => {
            expect(attributes[SemanticAttributes.NET_PEER_NAME]).to.equal('localhost');
        });

        it('should get hostname from url', () => {
            expect(attributes[SemanticAttributes.NET_PEER_PORT]).to.equal('9200');
        });

        it('should set net.transport', () => {
            expect(attributes[SemanticAttributes.NET_TRANSPORT]).to.equal('IP.TCP');
        });
    });

    context('getPort', () => {
        it('should get port', () => {
            const result = Utils.getPort('3030', 'http:');
            expect(result).to.equal('3030');
        });

        it('should get port from http protocol', () => {
            const result = Utils.getPort('', 'http:');
            expect(result).to.equal('80');
        });

        it('should get port from https protocol', () => {
            const result = Utils.getPort('', 'https:');
            expect(result).to.equal('443');
        });
    });

    context('normalizeArguments', () => {
        it('should normalize with callback only', () => {
            const callbackFunction = () => {};
            // @ts-ignore
            const [params, options, callback] = Utils.normalizeArguments(callbackFunction);

            expect(params).to.be.empty;
            expect(options).to.be.empty;
            expect(callback).to.be.equal(callbackFunction);
        });

        it('should normalize with params only', () => {
            // @ts-ignore
            const [params, options, callback] = Utils.normalizeArguments({ index: 'test' });

            expect(params).to.deep.equal({ index: 'test' });
            expect(options).to.be.undefined;
            expect(callback).to.be.undefined;
        });
    });

    context('getIndexName', () => {
        it('should accept index string', () => {
            const index = Utils.getIndexName({ index: 'test' });
            expect(index).to.equal('test');
        });

        it('should accept index array', () => {
            const indexes = Utils.getIndexName({ index: ['index1', 'index2'] });

            expect(indexes).to.equal('index1,index2');
        });

        it('should accept no index', () => {
            const undefinedParams = Utils.getIndexName(undefined);
            const emptyObject = Utils.getIndexName({});

            expect(undefinedParams).to.be.undefined;
            expect(emptyObject).to.be.undefined;
        });

        it('should ignore unexpected index', () => {
            const functionIndex = Utils.getIndexName({ index: () => {} });
            const objectIndex = Utils.getIndexName({ index: {} });

            expect(functionIndex).to.be.undefined;
            expect(objectIndex).to.be.undefined;
        });
    });

    context('startSpan', () => {
        const tracerMock = {
            startSpan: (name, options?, context?): any => {},
            startActiveSpan: () => {},
        };
        it('should start span with client kind', () => {
            const startSpanStub = stub(tracerMock, 'startSpan');

            Utils.startSpan({
                tracer: tracerMock,
                attributes: { testAttribute: 'testValue' },
            });

            assert.calledOnce(startSpanStub);

            const [operation, options] = startSpanStub.getCall(0).args;

            expect(operation).to.equal('elasticsearch.request');
            expect(options.kind).to.equal(SpanKind.CLIENT);
            expect(options.attributes[SemanticAttributes.DB_SYSTEM]).to.equal('elasticsearch');
            expect(options.attributes.testAttribute).to.equal('testValue');
        });
    });
});
Example #6
Source File: toMatchSnapshot.test.ts    From earl with MIT License 5 votes vote down vote up
describe('toMatchSnapshot', () => {
  const makeDummyTestRunnerCtx = (): TestRunnerCtx => ({
    afterTestCase: spy(),
    beforeTestCase: spy(),
    testInfo: {
      suitName: ['Dummy suit'],
      testName: 'works',
      testFilePath: '/tests/dummy.test.ts',
    },
  })

  class DummyControl extends Control<any> {
    testRunnerCtx = makeDummyTestRunnerCtx()
    assert = spy() as any
    fail = spy() as any
  }

  it('creates new snapshots', () => {
    const dummyCtrl = new DummyControl('test123', false)
    const dummyCompareSnapshot: CompareSnapshot = spy(() => {
      return { success: true } as any
    })

    toMatchSnapshot(dummyCtrl, { compareSnapshot: dummyCompareSnapshot, env: {} })

    expect(dummyCompareSnapshot).to.have.been.calledOnceWithExactly({
      actual: 'test123',
      name: 'Dummy suit works',
      updateSnapshotMode: 'new',
      snapshotFilePath: path.normalize('/tests/__snapshots__/dummy.test.snap'),
    })

    expect(dummyCtrl.assert).to.have.been.calledOnceWithExactly({ success: true, negatedReason: '-', reason: '-' })
  })

  it('matches existing snapshots', () => {
    const dummyCtrl = new DummyControl('test123', false)
    const dummyCompareSnapshot: CompareSnapshot = spy(() => {
      return { success: false, actual: 'test123', expected: 'abc' } as any
    })

    toMatchSnapshot(dummyCtrl, { compareSnapshot: dummyCompareSnapshot, env: {} })

    expect(dummyCompareSnapshot).to.have.been.calledOnceWithExactly({
      actual: 'test123',
      name: 'Dummy suit works',
      updateSnapshotMode: 'new',
      snapshotFilePath: path.normalize('/tests/__snapshots__/dummy.test.snap'),
    })
    expect(dummyCtrl.assert).to.have.been.calledOnceWithExactly({
      success: false,
      actual: 'test123',
      expected: 'abc',
      reason: "Snapshot doesn't match",
      negatedReason: '-',
    })
  })
})
Example #7
Source File: example.test.ts    From ardrive-cli with GNU Affero General Public License v3.0 4 votes vote down vote up
// Describe the function or behavior to test
describe('The basicInputOutputExample function', () => {
	// Define input
	const input = 42;

	// Define expectedOutput
	const expectedOutput = 1596;

	// Basic Mocha/Chai unit test example
	it('returns the expected output', () => {
		const actual = basicInputOutputExample(input);
		expect(actual).to.equal(expectedOutput);
	});

	// Asynchronous mocha/chai example
	it('asynchronously returns the expected output', async () => {
		const actual = await asyncInputOutputExample(input);

		// Returning anything to `it()` will conclude an async test
		return expect(actual).to.equal(expectedOutput);
	});

	// To more easily be used with Sinon, use test function inside of an object
	const objectWithExampleFunctions = { basicInputOutputExample };

	// Sinon spy example
	it('returns correct output when checked by Sinon spy', () => {
		// Setup spy
		const sinonSpy = spy(objectWithExampleFunctions, 'basicInputOutputExample');

		// Run test as normal
		const actual = objectWithExampleFunctions.basicInputOutputExample(input);
		expect(actual).to.equal(expectedOutput);

		// Verify spy calls with Chai
		expect(sinonSpy.calledWith(input)).to.be.ok;
		expect(sinonSpy.calledOnce).to.be.ok;
	});

	// Sinon stub example
	it('can be stubbed by a Sinon stub', () => {
		// Stub in a fake function
		stub(objectWithExampleFunctions, 'basicInputOutputExample').callsFake(() => 1337);

		const actual = objectWithExampleFunctions.basicInputOutputExample(input);

		// Verify stubbed output
		expect(actual).to.equal(1337);
	});

	// Sinon mock example
	it('can be used in a Sinon mock', () => {
		// Create mock
		const sinonMock = mock(objectWithExampleFunctions);

		// Setup mock expectations
		sinonMock.expects('basicInputOutputExample').once().returns(10101);

		const actual = objectWithExampleFunctions.basicInputOutputExample(input);

		// Confirm output with Chai
		expect(actual).to.equal(10101);

		// Verify mock expectations
		sinonMock.verify();
	});

	// Power-assert debugging example
	it('can provide detailed error output when used with the power-assert library', () => {
		// Comment out the regular Chai test
		// const output = basicInputOutputExample(input);
		// expect(output).to.equal(expectedOutput);

		// Put everything relevant inside a power-assert assertion
		// More info inside the assertion results in a more detailed output
		assert(basicInputOutputExample(input) === expectedOutput);

		/**
		 * This test has been left in a passing state because all tests must pass
		 * To view the detailed error output example, change above assertion to fail in some way
		 *
		 * For instance:
		 * assert(basicInputOutputExample(56) === expectedOutput);
		 * assert(basicInputOutputExample(input) !== expectedOutput);
		 *
		 * And then use: yarn power-assert -g 'power-assert'
		 */
	});
});
Example #8
Source File: configLoader.test.ts    From language-tools with MIT License 4 votes vote down vote up
describe('ConfigLoader', () => {
    function configFrom(path: string) {
        return {
            compilerOptions: {
                dev: true,
                generate: false
            },
            preprocess: pathToFileURL(path).toString()
        };
    }

    function normalizePath(filePath: string): string {
        return path.join(...filePath.split('/'));
    }

    async function assertFindsConfig(
        configLoader: ConfigLoader,
        filePath: string,
        configPath: string
    ) {
        filePath = normalizePath(filePath);
        configPath = normalizePath(configPath);
        assert.deepStrictEqual(configLoader.getConfig(filePath), configFrom(configPath));
        assert.deepStrictEqual(await configLoader.awaitConfig(filePath), configFrom(configPath));
    }

    it('should load all config files below and the one inside/above given directory', async () => {
        const configLoader = new ConfigLoader(
            (() => ['svelte.config.js', 'below/svelte.config.js']) as any,
            { existsSync: () => true },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        await assertFindsConfig(
            configLoader,
            '/some/path/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/aside/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/below/comp.svelte',
            '/some/path/below/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/below/further/comp.svelte',
            '/some/path/below/svelte.config.js'
        );
    });

    it('finds first above if none found inside/below directory', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            {
                existsSync: (p) =>
                    typeof p === 'string' && p.endsWith(path.join('some', 'svelte.config.js'))
            },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        await assertFindsConfig(configLoader, '/some/path/comp.svelte', '/some/svelte.config.js');
    });

    it('adds fallback if no config found', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => false },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        await configLoader.loadConfigs(normalizePath('/some/path'));

        assert.deepStrictEqual(
            // Can't do the equal-check directly, instead check if it's the expected object props
            // of svelte-preprocess
            Object.keys(
                configLoader.getConfig(normalizePath('/some/path/comp.svelte'))?.preprocess || {}
            ).sort(),
            ['defaultLanguages', 'markup', 'script', 'style'].sort()
        );
    });

    it('will not load config multiple times if config loading started in parallel', async () => {
        let firstGlobCall = true;
        let nrImportCalls = 0;
        const configLoader = new ConfigLoader(
            (() => {
                if (firstGlobCall) {
                    firstGlobCall = false;
                    return ['svelte.config.js'];
                } else {
                    return [];
                }
            }) as any,
            {
                existsSync: (p) =>
                    typeof p === 'string' &&
                    p.endsWith(path.join('some', 'path', 'svelte.config.js'))
            },
            path,
            (module: URL) => {
                nrImportCalls++;
                return new Promise((resolve) => {
                    setTimeout(() => resolve({ default: { preprocess: module.toString() } }), 500);
                });
            }
        );
        await Promise.all([
            configLoader.loadConfigs(normalizePath('/some/path')),
            configLoader.loadConfigs(normalizePath('/some/path/sub')),
            configLoader.awaitConfig(normalizePath('/some/path/file.svelte'))
        ]);

        await assertFindsConfig(
            configLoader,
            '/some/path/comp.svelte',
            '/some/path/svelte.config.js'
        );
        await assertFindsConfig(
            configLoader,
            '/some/path/sub/comp.svelte',
            '/some/path/svelte.config.js'
        );
        assert.deepStrictEqual(nrImportCalls, 1);
    });

    it('can deal with missing config', () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => false },
            path,
            () => Promise.resolve('unimportant')
        );
        assert.deepStrictEqual(
            configLoader.getConfig(normalizePath('/some/file.svelte')),
            undefined
        );
    });

    it('should await config', async () => {
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => true },
            path,
            (module: URL) => Promise.resolve({ default: { preprocess: module.toString() } })
        );
        assert.deepStrictEqual(
            await configLoader.awaitConfig(normalizePath('some/file.svelte')),
            configFrom(normalizePath('some/svelte.config.js'))
        );
    });

    it('should not load config when disabled', async () => {
        const moduleLoader = spy();
        const configLoader = new ConfigLoader(
            () => [],
            { existsSync: () => true },
            path,
            moduleLoader
        );
        configLoader.setDisabled(true);
        await configLoader.awaitConfig(normalizePath('some/file.svelte'));
        assert.deepStrictEqual(moduleLoader.notCalled, true);
    });
});