sinon | Test spies , stubs and mocks for JavaScript | Unit Testing library
kandi X-RAY | sinon Summary
kandi X-RAY | sinon Summary
Test spies, stubs and mocks for JavaScript.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Create a sandbox .
- Create an instance of assertions .
- Wrap function with a function and return it
- Stub property .
- Restores a property on the object .
- Returns a Promise for the given execor .
- Triggers a method on a props object .
- Creates a proxy call .
- Create a stub stub .
- DOM walk function .
sinon Key Features
sinon Examples and Code Snippets
function saySecret() {
return '🤫';
}
export function outer() {
return saySecret();
}
import rewire from 'rewire';
import sinon from 'sinon';
describe('71285081', () => {
it('should pass', () => {
import * as sinon from 'sinon';
import someModule from 'someModule';
describe("Something", () => {
let sandbox: sinon.SinonSandbox;
beforeEach('setup sandbox', function() {
sandbox = sinon.createSandbox();
}
import { mount } from '@vue/test-utils'
import sinon from 'sinon'
const spy = sinon.stub()
mount({
render: null,
destroyed() {
spy()
}
}).destroy()
expect(spy.calledOnce).toBe(true)
var chai = require('chai');
var qldb = require('amazon-qldb-driver-nodejs');
var sinon = require("sinon");
class VehicleRegistration {
constructor() {
var serviceConfigurationOptions = {
region: "us-east-1",
import * as functions from 'firebase-functions';
export const onCalculate = functions.https.onRequest((request, response) => {
const param1 = request.body.param1;
const param2 = request.body.param2;
response.status(200).send(calc
it('should create the message', async () => {
// Create stub for response to create method:
const createStub = sinon.stub().resolves({
// mocked value
});
// Stub the value "messages" to return an object that has
const AWS = require('aws-sdk');
const sinon = require('sinon');
const ddb = new AWS.DynamoDB.DocumentClient();
const getStub = sinon.stub(AWS.DynamoDB.DocumentClient.prototype, "get");
getStub.callsFake((params, cb) => {
cb(null, {
const AWS = require('aws-sdk');
const SQS = new AWS.SQS();
exports.handler = () => {
return SQS.deleteMessage({ foo: 'bar' }).promise();
};
const sinon = require('sinon');
const expect = require('chai').expe
// This is the bit I was missing, we need to tell sinon to take in a
// function/callback and immediately call it.
sandbox.stub(microsoftTeams, 'initialize').callsFake((callback) => callback());
sandbox.stub(microsoftTeams.authenticati
const b = require('./b');
function aGetResult() {
return b.getInfo();
}
exports.aGetResult = aGetResult;
const c = require('./c');
function getInfo() {
return getDetailInfo();
}
function getDetailInfo() {
Community Discussions
Trending Discussions on sinon
QUESTION
I'm working with Electron and Johnny-Five to process some data I read with my Arduino Mega 2560 and I'm having some trouble testing my Arduino's connection.
This is the method I want to test (ignore the awful signature):
...ANSWER
Answered 2022-Mar-22 at 06:25The typical approach would be moving the done
callback into the event handler. In this way, the test will wait until the callback is called. If the ready
event is not fired, the callback won't be called and the test will timeout with an error after 2 seconds.
This means that you don't need to explicitly assert that the event f
is called, and in fact, you don't event need to spy on it.
QUESTION
W.r.t. How to mock firestore with mocha how do I mock the following firestore query using sinon?
...ANSWER
Answered 2022-Feb-27 at 10:47import * as _chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
import * as admin from "firebase-admin";
import * as _sinon from 'sinon';
_chai.use(chaiAsPromised);
var expect = _chai.expect;
const db: FirebaseFirestore.Firestore = admin.firestore();
describe("Test with mock firestore", () => {
var docRefStub;
beforeEach(() => { docRefStub = _sinon.stub(db, "doc");});
afterEach(() => {db.doc.restore();});
it("Test should pass with valid request params", async () => {
const expectedString = "Hello World!!!";
const testCollection = {
"/Client/123/Store/789": {
data: 1,
moreData: "Hello World!!!"
}
}
const setSpy = _sinon.spy();
docRefStub.callsFake(fakeFsDoc(testCollection, setSpy));
await callAFunction("123", "789");
expect(setSpy.called).to.be.true;
expect(setSpy.getCall(0).args[0].data).to.not.be.null;
expect(setSpy.getCall(0).args[0].moreData).to.deep.equal(expectedString);
}
});
QUESTION
I have the following code
...ANSWER
Answered 2022-Feb-03 at 22:34You need some way of injecting a stub so that your class instance calls that instead of the external library. This answer elaborates some alternatives. The alternative to injecting stubs is to replace the entire module you are importing. This is called using a link seam. This answer shows one way and lists various module loaders that help you do so.
Personally, I have slowly moved away from module mocking techniques and try to keep myself in the land of dependency injection (alternative 1), since that works regardless of the underlying environment and any beginning programmer can read the tests. The least invasive way could simply be something like this:
QUESTION
This is one of the more complex scenarios I've encountered yet. I have a function that I need to test, this function is nested in a complex puzzle of functions. I need to stub this function, and set a value inside the variable
inside.
For reasons I'm not allowed to share here, the variable inside the publishEvent()
method is undefined during test run, I need a way to set the value for this variable during test in order for me to test the if block of code in the function.
I summarized the whole file because I can't share the code here due to NDA, sorry if the question is not detailed enough. Maybe using sinon I can directly set the value for this variable in the publishEvent
function.
ANSWER
Answered 2022-Jan-29 at 07:59You need a way of controlling what library.fetchData()
outputs. Either you need a way of injecting a substitute for that library (easiest option) or you need to employ a link seam (environment dependant, requires extra lib) - substituting the library with a fake one at the module loading level.
You can check out this SO answer to a nearly identical question for details.
QUESTION
I am using sinon to mock a return for a function and here is my code:
...ANSWER
Answered 2022-Jan-22 at 17:56resolves
returns a promise. The equivalent method in sinon to return a value is .returns
:
QUESTION
I'm trying to stub a function using sinon. The function has the following signature
...ANSWER
Answered 2022-Jan-21 at 01:15According to the docs, you can't stub an existing function.
You can:
QUESTION
I would like to make an unit test for a module that is using jsonfile
to read the data.
ANSWER
Answered 2021-Oct-22 at 20:07ES modules cannot be stubbed.
You can however wrap the functionality you want to stub in a class or object and export that and then you can stub methods on it using Sinon.JS or other libraries.
For getting started with Sinon.JS in Deno I suggest checking out Integration with testing libraries | Testing | Manual | Deno which references a sinon_example.ts.
QUESTION
So i have a very simple class which does the following:
- Adds an event handler on an element on it's creation
- The event handler is an instance method of the class
- I need a
cleanup
method to remove the handler on demand
ANSWER
Answered 2022-Jan-16 at 13:30You can stub
TestClass
's prototype.
QUESTION
I'm trying to write unit tests for a functional component I've recently written. This component makes use of multiple hooks, including, useState
, useEffect
and useSelector
. I'm finding it very difficult to write tests for said component since I've read that it's not good practice to alter the state but only test for outcomes.
Right now I'm stuck writing pretty simple unit tests that I just can't seem to get working. My goal for the first test is to stub AccessibilityInfo isScreenReaderEnabled
to return true so that I can verify the existence of a component that should appear when we have screen reader enabled. I'm using sinon
to stub AccessibilityInfo
but when I mount my component the child component I'm looking for doesn't exist and the test fails. I don't understand why it's failing because I thought I had stubbed everything properly, but it looks like I'm doing something wrong.
I'll add both my component and test files below. Both have been stripped down to the most relevant code.
Home-Area Component:
...ANSWER
Answered 2021-Dec-19 at 03:57It probably is because the promise is not resolving before you check that the component exists. You can read more about it here https://www.benmvp.com/blog/asynchronous-testing-with-enzyme-react-jest/
try it like this
QUESTION
I'm trying to make a simple test to get to know unit tests using mocha.
Folder Structure
- node_modules
- package.json
- package-lock.json
- testA.ts
- testA.spec.ts
- tsconfig.json
tsconfig.json
...ANSWER
Answered 2021-Nov-19 at 15:10I found the solution. Inside package.json
I added the require for mocha:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install sinon
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page