Questions tagged [mocking]

Mocking and faking techniques are employed to isolate code or components, thus ensuring that unit tests solely evaluate the testable unit of code. In doing so, these methods prevent the utilization of other components or dependencies within an application. However, it is worth noting that mocking stands apart from faking due to its ability to be inspected and used for asserting test results.

Testing file uploads with AngularJS unit testsAngularJS unit testing for

Unit tests in AngularJS can easily mock XHR requests using $httpBackend, making it convenient for testing. I recently encountered a situation where I needed to mock XHR for file uploads, but faced some challenges. Take a look at the following code snippe ...

Using Sinon to create a mock of a function

I'm having trouble figuring out a simple task like the one below: render() { return ( <div className="messageDetail"> <div className="messageForm" > Name: <input id="senderMsgName" value={this.props.nameVa ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

I wonder how the angular.mock.module function identifies which specific module to target for mocking its dependencies

I'm currently exploring the functionality of angular.mock.module (sometimes referred to as window.module) and how it operates. I've grasped that its primary purpose is to load a module in tests, which is straightforward: beforeEach(angular.mock. ...

Tips for seamlessly incorporating MongoMock with Pymongo-Flask

Looking to create unit tests for our mongo code using mongomock as the backend. However, facing a challenge with Flask-PyMongo which has a convenience class (find_one_or_404) added on top of the Collection class, complicating straight MongoMock substitut ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

I'm having difficulty mocking a function within the Jest NodeJS module

I have a module in NodeJS where I utilize a function called existsObject to validate the existence of a file in Google Storage. While testing my application with Jest 29.1.2, I am attempting to create a Mock to prevent the actual execution of this functio ...

How can I simulate an fs.readdirSync function call in Jest while incorporating withFileTypes, utilizing filter and map?

In Jest, I am trying to figure out how to mock the fs.readdirSync method within this function. export const getDirectoryFiles = async (directory) => { return fs .readdirSync(directory, { withFileTypes: true }) .filter(dirent => !dirent.isDirect ...

Testing a function within a class using closure in Javascript with Jest

Currently, I am attempting to simulate a single function within a class that is declared inside a closure. const CacheHandler = (function() { class _CacheManager { constructor() { return this; } public async readAsPromise(topic, filte ...

Mockery Madness - Exploring the art of mocking a function post-testing a route

Before mocking the process function within the GatewayImpl class to return the 'mockData' payload, I need to ensure that all routes are tested. import payload from './payloads/payloadRequire'; // payload for request import {GatewayImpl} from '../ ...

What is the best way to simulate a library in jest?

Currently, I am attempting to simulate the file-type library within a jest test scenario. Within my javascript document, this particular library is utilized in the subsequent manner: import * as fileType from 'file-type'; .... const uploadedFileType = fi ...

Can one mimic a TypeScript decorator?

Assuming I have a method decorator like this: class Service { @LogCall() doSomething() { return 1 + 1; } } Is there a way to simulate mocking the @LogCall decorator in unit tests, either by preventing it from being applied or by a ...

Creating test cases for a third-party CLI package

I have successfully created a command-line interface (CLI) program using yargs. I have managed to cover test cases for all the functions exported by the application. However, there seems to be a gap in the test coverage from lines 12-18. Can you provide i ...

Having trouble with Angular 2 and Ionic2 mocks? Getting an error message that says "No provider

Currently in the process of creating a spec.ts file for my application. The challenge I'm facing is related to using the LoadingController from ionic-angular. In order to configure the module, it requires providing the LoadingController (due to its pr ...

How to test onSubmit with react-testing-library on react-final-form

I put together a form using react-final-form, yup, and Material-ui. My testing tools include Jest, and @testing-library/react. Summary: Is there a method to mock and test just the onSubmit function without dealing with the validate functionality? Is there ...

Ways to test and simulate a $timeout function during unit testing

Is there a way to simulate the timeout function being called in this code snippet? $scope.submitRequest = function () { var formData = getData(); $scope.form = JSON.parse(formData); $timeout(function () { $('#submitForm').click(); ...

What is the best way to run tests on this code using Jest?

Currently deep diving into ReactJS testing and struggling to tackle the component showcased below https://i.stack.imgur.com/jaEis.png Running jest with coverage reveals a gap from line 8 to 10 despite using data-testid for test execution, which seems pecu ...

Struggling to simulate a named function being exported with jest / react-testing-library when rendering a page in nextjs

I have been attempting to mock a named imported function in a NextJS page, but so far all my efforts from various sources have been unsuccessful. I tried to replicate this by using create-next-app with --example with-jest and minimal code as shown below: ...

Disregard the patch decorator at the class level for a specific test

I am currently dealing with a class in a module structured like this: class Foo: def bar1(self) -> str: return "bar1" def bar2(self) -> str: bar = bar1() return bar def bar3(self) -> str: bar ...

Create a simulated class to serve as a property within a service

Currently, I'm working on an Ionic application and have created an AlertService class with two properties: messageAlert: Alert; errorAlert: Alert; The Alert class belongs to the Ionic framework, so I cannot modify it. To mock the Alert class, I came up w ...

Utilizing WireMock to simulate HTTP server responses. Error finding file with WireMock

Recently began using wiremock and encountered a situation where I need to mock a GET request with a specific json response. When including the json in the expected response like this; .withBodyFile("product.json")) I'm getting an error saying java. ...

"Creating a mock method in a test file located in a separate directory using Python

Encountering challenges while trying to mock a method, as the mock function is actually overwriting it. In app/tests/test_file.py we currently have the following unit test: @mock.patch('app.method', return_value='foo') def test(self, ...

Guide to simulating a scope in an Angular unit test using a directive instead of a controller

Recently, I have been working on understanding how to mock a $scope and controller using the $controller constructor. var scope = rootScope.$new(); it('should contain a testVar value at "test var home"', function(){ homeCtrl = $controller(&a ...

I am looking to retrieve information on method calls for a mock class in Python. How can I achieve

I have a class called Client that provides a service through its getResponse method. This class is utilized by other classes. I am writing unit tests for the Driver class which utilizes the Client class. Using mock.patch, I substitute the Client class with ...

Guide to testing my-sql database routes in an express application

Trying to test my NodeJS REST API has been a challenge due to most of my routes involving calls to a MySQL database. I've considered mocking or stubbing the database using Sinon, but have not had much success. Making real database calls in tests is no ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, data){ ...

Attempting to revert the imported module back to its initial/default mock configuration

When working on my test file, I utilize a folder named mocks which contains various exported functions. Most of the time, I rely on the mocks folder to perform all necessary tasks. However, there is one scenario where I need to adjust the return value to a ...

Is it possible to modify a method without altering its functionality?

I am currently attempting to verify that a pandas method is being called with specific values. However, I have encountered an issue where applying a @patch decorator results in the patched method throwing a ValueError within pandas, even though the origin ...

Creating delays in a Node.js server to replicate lagginess

I am currently working on developing a tool to replicate scenarios involving slow webservers. Inspiration behind creating a mock server Our frontend application communicates with 3 different webservers - X, Y, and Z all under the same domain. For example, ...

Guide on mocking Material-UI withWidth HOC

If I have a component wrapped in Material-UI's withWidth HOC, how can I use jest to mock withWidth's isWidthUp function and make it return a specific boolean value? System Under Test (SUT) import React, { Component } from 'react'; imp ...

teasing es6 imports in unit testing

Imagine a scenario where we have a file named source.js that needs to be tested: // source.js import x from './x'; export default () => x(); The unit test code for this file is quite simple: // test.js import test from 'ava'; import source from './s ...

What occurs when a python mock is set to have both a return value and a series of side effects simultaneously?

I'm struggling to comprehend the behavior of some test code. It appears as follows: import pytest from unittest.mock import MagicMock from my_module import MyClass confusing_mock = MagicMock( return_value=b"", side_effect=[ Connectio ...

Examining AngularJS Jasmine Promises in IsolationDive into the world

Seeking help for testing a mocked Service with chained promises. Factory for Testing app.factory('factory', [ 'service', function( service ){ var baz; return { updateMe: function( updateObj ){ // do stuff with updateObj con ...

Jesting supplier, infusing elements

I find myself in a complex situation that I will do my best to explain, even if it may seem confusing. Imagine I have a customized provider called actionProvider within the module named core. This provider has the ability to register actions and then exec ...

Jest's JavaScript mocking capability allows for effortless mocking of dependent functions

I have developed two JavaScript modules. One module contains a function that generates a random number, while the other module includes a function that selects an element from an array based on this random number. Here is a simplified example: randomNumbe ...

Playfully imitating cross-fetch

I am currently running tests on a Next/React project using Jest with Node. I have also implemented cross-fetch in my project. However, I encountered an issue when trying to mock cross-fetch for a specific component: import crossFetch from 'cross-fetch' je ...

Update a class from a separate module in Python using monkey patching

I have a class named bar in module A. class bar(): def __init__(item1, item2): self.item1 = item1 self.item2 = var2 def method_a(self): pass def method_b(self): pass bar_ = bar("examp ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning correctly, ...

Exploring AngularJS Protractor End-to-End Mocking

In my Angular SPA, I am retrieving data from a node backend that is fully covered with tests. To mock the Angular HTTP calls, I want to implement something like this: Api = $injector.get('Api'); sinon.mock(Api, 'getSomethingFromServer' ...

Having trouble with @aws-sdk/client-ssm (AWS SDK v3) timing out in Jest tests in Node.js

When I mock AWS SDK v3, my test cases are timing out. However, everything works fine for GetParameterCommand, but not for GetParametersCommand. Below is how my sdk file looks: const { SSMClient, GetParametersCommand } = require('@aws-sdk/client-ssm&a ...

Unit testing for Angular service involving a mock Http GET request is essential for ensuring the

I am seeking guidance on how to test my service function that involves http get and post calls. I attempted to configure the spec file by creating an instance of the service, and also consulted several sources on creating a mockhttp service. However, I enc ...

Struggling to locate a suitable mock server that can deliver JSON responses for a specific URL that has been predetermined

I have encountered a challenge in my frontend app development using vue.js. I need to find a mock backend server (without mocking it on the front end). My app is capable of making HTTP requests, specifically GET and PATCH are the methods of interest. I am ...

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test', () => { ...

Tips for identifying changes in APIs during the simulation of end-to-end tests?

I am seeking to establish a strong e2e testing framework for our team's project, but I am struggling to find a straightforward solution to the following question: When all calls are mocked, how can we effectively detect if the actual model of the objects ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippet of the code t ...

What is the most Pythonic way to check if a function has been called with a specific argument in Python?

Looking at my Django codebase, I have an endpoint that performs various tasks. My goal now is to verify if this endpoint is calling the function do_metadata_request with a specific token. Here's the function for reference: def do_metadata_request(url_info, ...

Unable to modify module variable through monkey patching in Python unit tests

I am currently testing the module: package/module.py DATA_PATH = os.path.join(os.path.dirname(__file__), "data") class SomeClass: def __init__(self): self.filename = os.path.join(DATA_PATH, "ABC.txt") within my tests in module_test.py I have ...