Questions tagged [sinon]
Sinon is a mocking framework for JavaScript, which can create spies, stubs and mocks.
2,834
questions
0
votes
0
answers
17
views
How do I stub this js function
How do I stub the responseFromRegisterAirQloud in
tenant.toLowerCase(),
"airqloud",
AirQloudSchema
).register(modifiedBody);
The getModelByTenant Function is ...
0
votes
1
answer
28
views
Stubbing slack alert usinng sinon not working
const sinon = require('sinon');
const URL = process.env.slackUrl;
const slack = require('slack-notify')(URL);
describe('stub slack alert',()=>{
it('',()=>{
sinon.stub(slack, 'alert')
})
})
I ...
0
votes
0
answers
46
views
TypeError: ES Modules cannot be stubbed - Sinon
Stubbing with Sinon returning an error for named function exports and it's working as expected for default function exports.
In the code below, foo1Stub = Sinon.stub(foos1, "foo1"); causing ...
2
votes
1
answer
26
views
Mocking react custom hook with sinon stub
I have a custom hook with that returns api calls. It looks like this:
export const useApiData = () => {
const queryClient = useQueryClient();
const [networkError, setNetworkError] = ...
0
votes
0
answers
17
views
How to fix parent context unavailable when using proxyquire with ES6 import statement?
I have the following file to test which is the migration_repository.js
import {getDatabaseName} from "./maria_db_connector"
export default class MigrationRepository {
...
1
vote
0
answers
20
views
How to stub/mock statSync function of fs module in sinon
I've created a function to get folder stat and compare the created time. I'm trying to test it and in order to test all scenarios I'm trying to stub the return object of statSync. But I'm unable to do ...
0
votes
1
answer
24
views
Stub a function inside a function without passing it as an argument
I have the following code:
const {compose} = require('./compose');
const complicatedFunction = async function (argA, argB) {
const result = await getValue(argA)
const value = await getValue2(...
0
votes
0
answers
14
views
React test with multiple state change broke the render output
I have a component that accept 2 async callback function from caller. In this case ClassA is the caller.
I am creating unit test in the component.
My component has multiple state, different state will ...
1
vote
1
answer
34
views
Sinon cannot stub non-existent own property 'function'
I am trying to mock a module Database so that its getRecordDetails() member function would always return some fixed data. See below:
handler.js
const sinon = require("sinon");
const Database ...
0
votes
1
answer
21
views
using sinon stub to test a method on an object
I want to test a function inside an object. The code, lets call it someFile.js, is structured as below.
import someService from 'a-location';
const val = someService.getVal();
const AnObject = {
...
0
votes
0
answers
22
views
How to modify the behavior of a function using "sinon.stub"?
I'm using the oci-usageapi and I would like to intercept and change the behavior of the requestSummarizedUsages that is inside the usageapi.UsageapiClient.
However, when I try to do this:
const ...
1
vote
1
answer
20
views
How to jump time with Sinon fake timers? (like when switching tabs then coming back later)
Based on Sinon's fake-timers (previously called "lolex") documentation, I don't see an API to jump forward by an amount of time for animation frames, similar to what happens when we switch ...
0
votes
0
answers
23
views
sinon Fails to Stub a Module Function
I'm trying to stub a function call in a persistence layer. This module:
userService.js:
const { User, sequelize } = require('../../models')
const userIdFor = async (clearID) => {
return await ...
0
votes
0
answers
26
views
Sinon spies are not being called when calling API
Problem description
I am working on a big project that has a lot of code to improve. For obvious reasons I can not publish the real code here but I have tried to create a very small mock of the ...
1
vote
0
answers
57
views
How can I test a constant value with mocha, chai, sinon?
to everyone, that's my first time here so I hope to do all in the right way.
So, I'm writing unit tests for my app and nyc tell me that I have a file that is not 100% tested, that's a simple file to ...
0
votes
0
answers
16
views
Testing route using express-session with mocha
I have a POST route that expects an groupId, and with that, I'm basically generate cookies and session.
I use express, and express-session to create a session and it look something like this:
export ...
3
votes
1
answer
33
views
Cypress: assert argument of stubbed function with Regex
I have a stubbed method that is having the following structure printed in the Cypress console:
myMethod('start', Object{5})
I know that the object has a key, segmentB -> when console logging it in ...
0
votes
0
answers
36
views
Writing a JavaScript test for XMLHttpRequest
Whilst testing a function which uses Sinon's fakeXMLHttpRequest, when I run the test I get:
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)
...
0
votes
0
answers
18
views
mocking a httpClientProvider failing with TypeError: is not a constructor
Hi I am trying to write a test for the above code using mock-require.
const requiredService = require('./lib/requiredService');
const requiredServiceClient = requiredService.makeServiceClient({
...
-1
votes
1
answer
17
views
How to test an express.js ErrorHandler?
I'm trying to test the fail case for this function with TypeScript and Sinon, but I have not idea how. Any help?
public async findById(id: number): Promise<UserModel> {
const user = await ...
1
vote
1
answer
16
views
How to test non-awaited async function calls in mocha?
I want to write a mocha test suite for a reservation service that calls a postReservation service which runs asynchronously? How to test if the postReservation service was called?
async function ...
1
vote
1
answer
20
views
SINON Stub findall and scope at same time
I'm trying to mock my sequlize db call
Below is the example
it('mock db call', async() => {
sinon.stub(DBNAME, 'scope').resolves()
sinon.stub(DBNAME, 'findAll').resolves(dbDetails)
...
1
vote
0
answers
42
views
Sinon stub - stubbing an axios api generated with swagger
I have a file generated by swagger open api. I am writing some tests and using sinon stubs for the first time. I am wondering how can I stub an api call from a class:
export class Api<...
0
votes
0
answers
28
views
How to write test case for if condition using mocha node.js
I'm trying to write a unit test case for the below code. It's complaining that the line having if doesn't have a unit test covered. I get result from another function.
const data = result.map((...
0
votes
0
answers
33
views
Mocking standalone function of a module for testing using sinon
New to Typescript, need help with mocking with sinon
childModule.TS
export default function go(a:number){ return a * 2 }
ParentModule.ts
export {default as go } from './childModule'
testcandidate....
0
votes
0
answers
36
views
How to stub a exported function from different file that non-configurable & non-writable in node.js with Sinon
I use the Sinon library to write unit tests; however when I try to stub a function that is exported from a different file like 'something-helper.ts' and sometimes It throws an error from the related ...
1
vote
1
answer
48
views
sinon.restore in one file restores any top level stubs in another file
Service1:
const { Service2 } = require('../Service2.js');
const func1 = () => {
const result = Service2.func2();
return result;
}
const Service1 = { func1 };
module.exports = { Service1 };
...
0
votes
2
answers
59
views
How to use sinon to mock a function within a function?
yellow.js
async function yellow(
prop1,
prop2
) {
//does stuff and returns an array
return [1, 2, 3]
}
blue.js
const Yellow = require('./yellow')
async function blue(
prop1,
prop2
) {
...
0
votes
0
answers
43
views
Mocha test reporting Object.hasOwn is not a function
I am using mocha and sinon to test and I am using node 16.19.0
I am using Object.hasOwn in my code and the test is currently failing with:
"Object.hasOwn is not a function"
I'm not really ...
0
votes
0
answers
31
views
When (and how) should I remove a proxyquire/sinon mock
**edit: I restored the mocked function after test1, using sinon.restore(), but again, it feels unnecessary to restore all mocks when I just want to restore one.
Just wondering when and how I should ...
0
votes
2
answers
36
views
Sinon Stub is not throwing an error when fs.readFileSynch also throws an error
After going through all related issues regarding stubbing readFile/Sync with Sinon /Chai/ Mocha, the test is failing.
There's a basic getFile function that retrieves a file:
function getFile(path) {
...
0
votes
1
answer
47
views
Sinon - How do I stub a private member object's function? [duplicate]
Consider a class which I want to test
class A{
private b:B = new B();
function someFunction(){
b.someOtherFunction(); // prevent this call
return 42;
}
}
Class B{
function ...
0
votes
0
answers
12
views
How to I check the contents of a functionality of a web component function using sinon?
I am relatively new to web components and testing them. How do I test the functionality of a function?
createObjForStartBusiness() {
this.financingObj = [];
if (this.dropDownValue === common....
0
votes
0
answers
18
views
How to test if a function is called using open/wc testing with sinon?
I am new to web components, and am using LIT framework. I have been breaking my head trying to figure this out.
This is my function.
createObj() {
this.financingObj = [];
if (this.dropDownValue === ...
0
votes
0
answers
50
views
How can I stub a method on a object that is created at runtime
I am trying to stub a method on a object with sinon that seems to only exist at runtime.
const client = await createClientAsync(VatService.endpoint, { request: axiosIns }); const result = await client....
1
vote
1
answer
71
views
In a Cypress test how can I stub argument of a function
I am writing a Cypress integration test for a Google Optimize experiment and I would like to stub the experiment variant value provided by gtag library.
The value is provided as the argument of ...
0
votes
1
answer
36
views
How do I stub a callback function inside object parameter using sinon?
Working on project that uses a STOMP library called stompit. Had to make a change that adds the onReceipt callback which is provided via options parameter.
Basically the code looks like this:
...
2
votes
1
answer
45
views
How to write Qunit for attachEventBrowser in UI5
I have a code snippet for which I have to increase code coverage
Following is my controller-
I need to have statements in my qunit for the bold section
sap.ui.define([
"sap/ui/core/mvc/...
0
votes
1
answer
37
views
Stubbing other repository calls in current repository test
I am trying to write test cases for an Node.js backend project
The database is using pg-promise. I run into issue when trying to stub the repository and it tries to call other repositories.
Here is ...
0
votes
0
answers
43
views
Testing authenticated route with sinon never goes through to controller
I'm trying to unit test a expressjs route that should just check if the response has status with value 200 and has property 'success' set to true.
This response should be returned from the last method ...
2
votes
1
answer
647
views
jsonwebtoken 9.0.0 - getting error: TypeError: Cannot redefine property: decode - when trying to stub
so npm audit just found jsonwebtoken to have a security vulnerbility. The solution is to update to version 9.0.0 - which I did.
However, my mocha tests are not passing now. During a beforeEach, I am ...
0
votes
1
answer
72
views
How to return value of Sinon fake based on argument of function?
I'm trying to avoid use of older Sinon APIs and use Fakes only. Previously, I used to be able to mock the return value of a stub based on an argument like so:
sinon.stub().withArgs("arg1")....
1
vote
1
answer
105
views
How to mock ElasticSearch client specific method
I have code in which I make a call to elasticsearch indices stats. Tried mocking it following way but did not work.
esIndicesStatsStub = sinon.stub(Client.indices.prototype, 'stats').returns({
...
0
votes
1
answer
47
views
How to stub async module dependencies for jest
Let's say I have the following route:
import {example} from '../some/place'
const processRequest = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
...
1
vote
0
answers
49
views
Stubbing exported function with sinon, mocha, and swc fails
I am trying to stub the function exported from my ES module.
I used wildcard import(import * as) to stub it, and it works when ts-node is used for transpiling(mocha --require ts-node/register */**/*....
1
vote
0
answers
37
views
How to stub query helper method Mongoose?
I'm using Sinon to test my Express/Typescript application. In Mongoose I have models with query helper methods to make query chains.
I have this schema
export const articuloSchema = new Schema({
...
1
vote
0
answers
22
views
How to test mongoose methods using sinon fakes?
I have the following arrangement of tests using sinon, mocha and chai:
type ModelObject = {
name: string;
model: typeof Categoria | typeof Articulo | typeof Usuario;
fakeMultiple: () => ...
0
votes
1
answer
35
views
How do I use sinon stub a management client endpoint while using the Auth0 Management API node library?
I have the following code to try and stub out the Auth0 Management API function...
import {ManagementClient} from 'auth0';
import sinon from "sinon";
const component = new Auth0App();
const ...
0
votes
0
answers
40
views
Unit Testing using Sinon for document.addListener
I'm doing unit test for a function with document.addEventListener
document.addEventListener('keydown', this.rfidListener, false);
I try to use sinon.stub to mock addEventListener. But it fail to mock ...
0
votes
0
answers
30
views
undefined async handler using sinon.stub()
I know it's something obvious that I'm missing but I'm trying to write unit tests using mocha, chai and sinon for an async handler that's referencing another async service. Here's the code for what I'...