Jest's expect.any(Object) function is not able to match CancelToken

After converting some files in a project to TypeScript, I encountered a test failure related to the following code:

expect(mocks.request).toHaveBeenCalledWith({
  headers: { 'Content-Type': 'bar' },
  method: 'put',
  params: file.slice(),
  path: 'foo',
  responseType: 'text',
  cancelToken: expect.any(Object),
});

The error message is as follows:

  expect(jest.fn()).toHaveBeenCalledWith(...expected)

    - Expected
    + Received

      Object {
    -   "cancelToken": Any<Object>,
    +   "cancelToken": CancelToken {
    +     "promise": Promise {},
    +   },
        "headers": Object {
          "Content-Type": "bar",

This particular section of code is being tested:

this.cancelToken = axios.CancelToken.source();

return request({
  method: 'put',
  path: presignedUrl,
  params: file.slice(),
  cancelToken: this.cancelToken.token,
  headers: {
    'Content-Type': contentType,
  },
});

I attempted to update the test using expect.anything(), like so:

cancelToken: expect.anything(),

Unfortunately, this modification led to another error:

    - Expected
    + Received

      Object {
    -   "cancelToken": Anything,
    +   "cancelToken": CancelToken {
    +     "promise": Promise {},
    +   },

Any suggestions on how to resolve this issue with my test code?

Note: I made sure to compare the value passed to the function request by adding a

console.log(this.cancelToken.token)
statement, and it remained consistent between the main branch and the new branch. Therefore, I am puzzled as to why Jest failed in this manner.

Answer №1

It turns out that my initial test was incorrect. After deleting the line responseType: 'text',, everything started working perfectly!

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

`Welcome to the World of AngularJS with IntelliJ IDEA`

Hey there! I'm currently diving into the world of Angular.js and IntelliJ IDEA, but seems like I've hit a roadblock. I'm attempting to create a basic "hello world" example from a book in the IDE, but it's just not cooperating. After dow ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

Error message: "TypeError when trying to append a child, even though the

I am encountering an issue with Shopify where I need to sort blog posts by a date different from the publish date. According to the Shopify Community Forums, the most effective way to achieve this is by utilizing liquid to input the information and then mo ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Collection of pictures with the ability to magnify

I'm attempting to add a zoom feature to my gallery using HTML, CSS, and JavaScript, but I'm unsure of the precise steps. The end result I'm aiming for is similar to the effect seen at this link: ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...

Oops! Looks like you forgot to include the "reducer" argument. It is necessary and should be either a function or an object of functions that can be passed to combineReducers

1 I'm currently working through the Redux tutorials on their website and I'm encountering an issue when trying to use combine reducers. When I run my code without using combine reducers, everything works fine. However, as soon as I include the s ...

Create intersecting lines on a SphereGeometry

In my attempt to draw lines on a THREE.mesh using a SphereGeometry for the geometry and a MeshBasicMaterial for the material, I encountered some challenges. Initially, I used the following code snippet: var segments = 32 var geometry = new THREE.SphereG ...

Error in NodeJS Mongoose: Undefined value causing inability to call the 'toString' method

I am having an issue with displaying the name of a Team from my database on the web page. Here is the code snippet I am using: var Team = require('../schemas/Team').Model; app.get('/match', function(req, res) { var key = 1359407087 ...

Converting JSON data into clickable URL links and retrieving information upon clicking

I have a dataset in JSON format. As I iterate through it, I'm inserting selected values into an HTML link element as shown below: getPatchList: function() { $.ajax({ url: "/returneddata" }).done(function(r ...

Controlling div elements using javascript

Is there a way to help me understand or identify my mistake? I seem to have an issue in my javascript and html code related to gathering user input for a flight. I'm trying to create a counter function to tally all flights (function counter()), but it ...

"Enable a smooth transition and switch the visibility of a div element when clicked

How to create a dropdown form with a transition effect that triggers on click of an element? Once triggered, the transition works smoothly but clicking again only hides the div element without triggering the transition. See the demo here: Check out the fu ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

Store my JSON data in a separate file and then reference it in my controller

Hello, I am currently working on an AngularJS application development project. Within my JSON data, I have information structured like this: angular.module('app', []).controller('MainController', ['$scope', function($scope) { ...

Identifying Errors in Meteor's Data Publications

I am currently working on a web application using Meteor and AngularJS 2. Take a look at the publication function below: Meteor.publish('abc', function () { // For throwing the meteor error according to the condition if(!this.userId) throw new ...

The JavaScript exec() RegExp method retrieves a single item

Possible Duplicate: Question about regex exec returning only the first match "x1y2z3".replace(/[0-9]/g,"a") This code snippet returns "xayaza" as expected. /[0-9]/g.exec("x1y2z3") However, it only returns an array containing one item: ["1"]. S ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

Adjust the state of an object by utilizing properties retrieved from a "ref"

I have an initial state object with coordinates x = 0 and y = 0, which I need to update once the html element, that the ref is attached to, is rendered. However, Typescript is throwing errors indicating that the properties I am trying to access in useEffe ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...