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.nameValue} onChange={this.props.handleNameChange}/>
          <br />
          Body: <input id="senderMsgBody" value={this.props.bodyValue} onChange={this.props.handleBodyChange}/>
          <br />
       </div>
     </div>
   );
 }
}

My goal is to test whether the onChange function is being called. How can I use sinon to mock this out, considering it is called using props? Once mocked, I will simulate it being called for testing purposes.

I started by creating this spy:

const handleBodyChangeSpy = sinon.spy();
and then expect this:
expect(handleBodyChangeSpy).to.have.not.been.called();

I could really use some guidance on how to accomplish this.

Answer №1

If you're working with ES6 and utilizing

class Component extends React.Component
, then you have the option to create a spy using
var spy = sinon.spy(Component.prototype, "handleBodyChange")
. This allows you to test your assertions on the spy object.

To learn more about creating spies, you can visit: http://sinonjs.org/releases/v1.17.7/spies/ (look for information under Creating spies: sinon.spy() Method Signatures).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the differences between Material-UI's makeStyles and withStyles when it comes to

One thing I've observed is that the naming convention for classes created with makeStyles and hooks looks like this: https://i.stack.imgur.com/HcDUc.jpg On the other hand, classes produced using withStyles and higher order components (HOC) follow a ...

Can someone clarify the actual version of webpack.js being used in my Ruby on Rails application with --webpacker=react configuration?

My tech stack includes Ruby 2.7.1, yarn 1.22.5, Rails 6.0.4.4, and node v16.13.1 I recently followed a tutorial on integrating React into my Rails project from this link The tutorial led me to install webpacker 4.3.0 automatically in my Gemfile.lock file ...

Instructions for adding a clear icon within Material-UI pickers in an input

I frequently utilize a Date picker that offers the option to clear, but only when the picker is open. https://i.stack.imgur.com/Y5kFI.png Perhaps it would be feasible to include a custom button like this: https://i.stack.imgur.com/BzvFw.png Alternative ...

Tips for manipulating an element's className with refs:

I have a text as well as a button. My goal is to create functionality where clicking the button will hide the text without relying on the use of state. class Test extends Component { constructor(props){ //codes } hide = () => { ...

Adjusting the font size on the Mui DatePicker's year picker for better styling and visibility

I've been struggling with customizing the styling of MUI's DatePicker, particularly the Year Picker. I experimented with two different methods for styling : Method 1 : Using MUI's createTheme() : MuiYearPicker: { styleOverrides: { ...

Utilizing Conditional Statements Within a Map Function

A DataGrid on my frontend application displays data fetched from a MongoDB backend. The data corresponds to keys defined in the MongoDB documents, each containing a set of boolean values. My goal is to check if any of these boolean values are true and disp ...

The implementation of the '@' import for Jest testing is crucial for enhancing the efficiency of test cases

Having an issue running tests for my React application that utilizes @ import like this import { something } from "@atoms"; I have successfully mapped it in the tsconfig.json file, and it works fine when I run the application (command: "web ...

The mystical event object will still be passed to event handlers even if it has not been explicitly

As I was assisting a colleague, I came across some code that seemed quite puzzling. Here's the gist of what it looked like: <button onClick={() => console.log(event)}>Click Me</button> The code consisted of an anonymous function that d ...

While running `Django manage.py test`, the `urls.py` file was not visible, even though it is detected

I have a django project structured like this: Base Directory | manage.py | configDir \ | settings.py , urls.py, wsgi.py |mainApp \ |urls.py , views, models etc. | tests \ |urlTest.py (To clarify, there is a django config dire ...

What is the process to enable a deployed React app (hosted in S3) to retrieve JSON data that is uploaded to an S3 bucket?

I'm in the process of creating a static React App that showcases API documentation. Utilizing Swagger for the backend (which is hosted separately on a lambda) to generate the JSON data model. I have another lambda set up to provide me with endpoint de ...

Using the useRef validation can lead to errors when trying to reference the current value against an input

Currently, the code is functioning well but an error alert from Typescript needs to be addressed. A warning pops up regarding the use of ref.current.value. ERROR 1. TS18048: 'ref.current' is possibly 'undefined'. To tackle this issue, ...

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Enhance your React Native app: Utilizing dynamic string variables with react-native-google-places-autocomplete query

I have encountered an issue while attempting to pass a dynamic country code to restrict search results. Here is the code in question: let loc = 'de' <GooglePlacesAutocomplete placeholder="Search" autoFocus={true} onPress ...

Tips for verifying the presence of a 3D model from Spline API within the DOM using Next.js

I am in the process of developing a brand new website and I have integrated a 3D model from spline, although it is taking quite some time to load. To improve user experience, I decided to implement a loader/Spinner. However, I'm facing the challenge o ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Uh oh! It appears that the Nextjs stripe-webhook api endpoint is missing. Error

Recently, I have been encountering a [404] POST http://localhost:3000/api/stripe-webhook error while listening on stripe. I am currently running the NextJs version "14.1.3". The stripe-webhook.ts file is located at 'app/api/stripe-webhook.t ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Frontend Will Not Be Able to Access Cloud Run Environment Variables when in Production

My current setup involves using docker to build an image through Google Cloud Build and Google Cloud Registry. I have Pub/Sub triggers in place to populate Cloud Run instances with new Docker images upon a successful build. The issue I am facing is that m ...

How can we declare and showcase a generic object with an unspecified number and names of keys in React using TypeScript?

I am facing a challenge with objects that have a 'comments' field. While all the other fields in these different objects have the same types, the 'comment' field varies. I do not know the exact number or names of the keys that will be p ...

Unable to upload multiple files using formidable in Node.js

app.post('/upload', function (req, res) { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { try{ if (files.file.name != '') { file_newname = dt.MD5(files.file.name ...