Unable to spy on the second and third call using Jest

I'm having trouble using spyOn on the second and third calls of a function in my jest test

I attempted to follow the documentation with this approach:

it("should succeed after retry on first attempt failure", async () => {
  jest.spyOn(nukiService, "lockDoors")
    .mockResolvedValueOnce(Promise.resolve({ status: 503 }))
    .mockResolvedValueOnce(Promise.resolve({ status: 200 }));

  expect((await nukiService.lockDoorsWithRetry()).status)
    .toBe(200);
});
    
it("should fail after 3 retries", async () => {
  jest.spyOn(nukiService, "lockDoors")
    .mockResolvedValueOnce(Promise.resolve({ status: 503 }))
    .mockResolvedValueOnce(Promise.resolve({ status: 503 }))
    .mockResolvedValueOnce(Promise.resolve({ status: 503 }));
    
  expect((await nukiService.lockDoorsWithRetry()).status)
    .toBe(424);
});

However, my test is failing due to timeout issues which I suspect are related to the spyOn not working as expected:

● NukiService › handle doors › should succeed after retry on first attempt failure

    thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

      85 |     });
      86 |
    > 87 |     it("should succeed after retry on first attempt failure", async () => {
         |     ^
      88 |       jest.spyOn(nukiService, "lockDoors")
      89 |         .mockResolvedValueOnce(Promise.resolve({ status: 503 }))
      90 |         .mockResolvedValueOnce(Promise.resolve({ status: 200 }));

      at services/nuki.service.spec.ts:87:5
      at services/nuki.service.spec.ts:18:3
      at Object.<anonymous> (services/nuki.service.spec.ts:5:1)

Answer №1

A timeout error is triggered by the test, suggesting that nukiService.lockDoorsWithRetry() is exceeding the designated time limit.

To troubleshoot this issue, delve into the inner workings of nukiService.lockDoorsWithRetry() to analyze its behavior and verify if it aligns with your expectations.

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

In Node.js, while running unit tests, the importing function is limited to read-only access

Having trouble mocking an async function in Jest? I followed the documentation and used mockResolvedValue, but encountered a read-only issue when trying to import my mock function from another file. Check out my code below: //index.js async function get ...

The Mat-slide-toggle resembles a typical toggle switch, blending the functionalities of

I am facing an issue with a `mat-slide-toggle` on my angular page. Even though I have imported the necessary values in the module, the toggle is displayed as a normal checkbox once the page loads. HTML: <div style="width:100%;overflow:hidden"> < ...

Capybara is throwing a NoMethodError - looks like something is

I need help with adding a tag to a tag field. To populate the tag field, I must either add ',' or press enter with a tag name such as "Ezgi,". Below are the steps I have outlined for this task. When(/^I enter "([^"]*)" on Label field$/) do |arg1 ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

Change validators dynamically according to conditions

Scenario: At the start, there is a single text box named Name1, a date picker called DOB1, and a check box labeled Compare. Both Name1 and DOB1 are mandatory. When the checkbox is clicked, two new form controls are dynamically included, named Name2 and DO ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

Encountered an error while loading resource: net::ERR_CONNECTION_REFUSED in Nodejs

I am currently working on a form in my angular 6 app with nodejs, utilizing nodemailer for sending emails. Unfortunately, I am encountering an error that reads: Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1 Below is the form ...

Issue Encountered in Laravel 5.1 When Running Test on User Password Mutator

A question about a password mutator: /** * Custom function to encrypt the user password. * * @param $password */ public function getPasswordAttribute($password) { $this->attributes[ 'password' ] = bcrypt($password); } I have a test c ...

What is the best way to ensure that two promises are both resolved before triggering a function from within a promise?

In my code, I have a forEach loop on a matches fetch that looks like this: matches => { matches.forEach(match => { Promise.all([this.teamService.getTeam(match._links.homeTeam.href)]) .then(team => { match. ...

Issue with Angular DevExtreme error popup

Currently, I am working on a project using Angular and DevExtreme. Whenever an error occurs, the error message seems to be hidden behind the popup form. Can anyone advise me on how to bring it to the front? Any help would be greatly appreciated. https://i ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...

The issue with the React Hook for window resize not updating remains unresolved

I have a React Hook designed to update the window size on resize, but it's not functioning correctly. Can someone please help explain why this is happening and provide guidance on how to utilize this hook in another component to create a Boolean value ...

What could be causing the malfunction of my button's event handlers?

Users can fill out a form in which they provide information about a grocery item they want to add to their cart. After completing the form, they can click on the "Add Item" button. Here's the form in my app.component.html: <form (ngSubmit)="a ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

Configuring VS Code's "tasks.json" file to compile all .ts files can be done by following these steps

Apologies if this question has been asked before, but could someone please redirect me to the relevant thread if so. I am wondering if it is possible to set up VS Code's "tasks.json" to automatically compile all .ts files within a folder. Currently, I ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

using the ts-migrate-mongoose package for migrating MongoDB

I'm currently working on a NestJS application and using ts-migrate-mongoose for database migration. The issue I'm facing is related to importing a user schema from outside of the migration folder (which is located in the root folder by default). ...

Using GraphQL to set default values in data within a useEffect hook can lead to never

Here's the code snippet that I'm working with: const [localState, setLocalState] = useState<StateType[]>([]); const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, { variables: { id: client && client.id ...