Testing with Jest in JavaScript shows the failure of a previously passing test when an object is moved to an external helper function

During my test setup, I initialize a player object in the beforeEach block. Within my test logic, every time I call jest.advanceTimersByTime(2001), the player.seekable.mock.calls count increases. As such, given that I make two calls to jest.advanceTimersByTime(2001), the total should be reflected as

player.seekable.mock.calls.length
equaling 2.

initPlayer.test.js

describe('testing', () => {
   let player, seekableEnd;
   
   beforeEach(() => {

       seekableEnd = 120;

       player = {
          currentTime: jest.fn(),
          seekable: jest.fn(() => {
             return {
                end: jest.fn().mockReturnValue(seekableEnd),
             };
          }),
       } 
   });

    it('should keep until the video has a seekable edge', async () => {
    
       seekableEnd = undefined;
       player.currentTime.mockReturnValue(10);

       await initPlayer();

       jest.advanceTimersByTime(2001);
       seekableEnd = 100;
       jest.advanceTimersByTime(2001);

       expect(player.seekable.mock.calls.length).toBe(2);
  });
});

I attempted to refactor my code by moving the player object into a helper function, rather than defining it directly within the test. However, upon using this helper in my test file, the

player.seekable.mock.calls.length
value is now 1 instead of 2 as it was previously defined in the direct test setup. The reason for this discrepancy eludes me.

player.js

export function getPlayer(data) {

       player = {
          currentTime: jest.fn(),
          seekable: jest.fn(() => {
             return {
                end: jest.fn().mockReturnValue(data.seekableEnd),
             };
          }),
       } 

    }

 export default getPlayer;

initPlayer.test.js

import { getPlayer } from './helpers/player';

describe('testing', () => {
   let player, seekableEnd;

   beforeEach(() => {

       seekableEnd = 120;

       const data = { seekableEnd };
       player = getPlayer(data);
   });

    it('should keep until the video has a seekable edge', async () => {

       seekableEnd = undefined;
       player.currentTime.mockReturnValue(10);

       await initPlayer();

       jest.advanceTimersByTime(2001);
       seekableEnd = 100;
       jest.advanceTimersByTime(2001);

       expect(player.seekable.mock.calls.length).toBe(2);   <---- this is 1 now when using the extracted player helper
  });
});

Answer №1

getPerson is not fetching the person data correctly. Consider modifying it to:

export function getPerson(data) {

   return {
      age: jest.fn(),
      name: jest.fn(() => {
         return {
            first: jest.fn().mockReturnValue(data.firstName),
            last: jest.fn().mockReturnValue(data.lastName),
         };
      }),
   } 
}

export default getPerson;

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

Error message encountered in node-schedule: Unable to read undefined property upon job restart

Using node-schedule, I have successfully scheduled jobs on my node server by pushing them into an array like this: jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url))); Everything is working as expected. When the designated date ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

I'm struggling to recreate basic JavaScript code with an Angular directive

I created a basic widget/snippet that replaces empty stars with filled stars upon hover. When the mouse moves away, it reverts to the default number of stars, and when clicked, it changes the default value based on the star clicked. While it's a strai ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

center the view on the specified element

Utilizing ReactJs, I am developing a horizontal timeline that showcases dates. For instance, there is a list of 100 elements, each containing a date and text content. The dates are displayed horizontally using flex-direction="row" and overflowX ...

Transfer the data from the For loop to JavaScript

As I develop a survey form through the ASP.NET MVC structure, I encounter a phase where I extract the survey questions from a model to the view. The model I have created is as follows: [NotMapped] public class QuizForService { public int M ...

Unlocking the secrets of capturing key presses before submitting with jQuery

I'm seeking help with creating an app that scans a barcode and displays the data on screen. I prefer not to use textboxes in order to prevent data editing. Currently, I have set up the enter key to be automatically sent at the end of the barcode scan ...

Attempting to relocate various containers

My task involves handling a group of randomly placed boxes on a webpage, each painted in random colors. I am currently attempting to enable their movement from one location to another. Despite being a seemingly simple task, my lack of familiarity with mous ...

Obtaining data from HTML input in Flask while dynamically altering the website's URL

I have a text box in my HTML code and I am trying to figure out how to retrieve the data that is entered into that box when a button is clicked. I have experience getting data from a form using the code snippet below: ex = request.form['example' ...

Error 400: The onCreate Trigger function for Cloud functions is experiencing issues with HTTP requests due to errors in the request

I am encountering an issue when attempting to add a trigger for Firestore OnCreate, as the deployment fails with HTTP Error: 400 stating that the request has errors. Essentially, my goal is to write to a new document if a record is created in a different ...

Transitioning from utilizing Jquery for post requests to implementing modern Promises

Currently, I am involved in a web application project that utilizes Flask and Python on the back-end with JavaScript on the front-end. I have been contemplating leveraging more modern styles like ES6/7 features such as Promises. In my development process, ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...

I am experiencing issues with my AJAX file and it seems to be

After creating a basic AJAX application to retrieve data from a PHP file using an ajax.js file, everything was uploaded to the server. However, upon accessing localhost/mypage, the expected results did not occur due to unforeseen issues. Below is the HTML ...

Tips for effectively utilizing nodejs soap

Here's the code snippet I've been working on: soap.createClient(url, function(err, client) { if(err) { res.status(500); return res.send(err); } client.GetMemberPIN({pUserName: 'r'}, function(error, result) { if(erro ...

Using jQuery to apply a class based on JSON data

This file contains JSON data with details about seat information. var jsonData = { "who": "RSNO", "what": "An American Festival", "when": "2013-02-08 19:30", "where": "User Hall - Main Auditorium", "seats": ["0000000000000000001111111 ...

Trouble with jQuery event.keyCode in detecting alphanumeric characters

I recently developed a script that is supposed to detect the key the user clicks and perform an action based on whether it is alphanumeric. However, I am encountering an issue as the script does not seem to be working as expected, and I am not receiving an ...

Tips for refreshing extensive JSON structures?

I receive product data from the server in JSON format, containing properties and nested arrays up to 4 levels deep. In the frontend, users can update values within these nested structures. Should I keep track of the path and reconstruct the entire JSON obj ...