Could my object exports be the issue? I'm new to JS and struggling to figure out why my test is not passing

Just dipping my toes into the world of Javascript and currently tackling objects and test driven development in my classes.

I've encountered a bit of trouble with my code and tests - not quite sure why they're failing. Initially, everything worked fine with just one object and its corresponding test, but adding a second object caused some issues.

Main:

const person1 = {name: "Louis"}
const person2 = {name: "Amber"}

module.exports = person1
module.exports = person2

Test Code:

const { TestScheduler } = require("jest")
const person1 = require('./family')
const person2 = require('./family')

describe('person objects', () => {
    test('I am in the family', () => {
        expect(person1.name).toEqual("Louis")
    })
    test('My sister is in the family', () => {
        expect(person2.name).toEqual("Amber")
    })
})

Test Outcome:

Debugger attached.
 FAIL  ./family.test.js
  person objects
    ✕ I am in the family (4 ms)
    ✓ My sister is in the family

  ● person objects › I am in the family

    expect(received).toEqual(expected) // deep equality

    Expected: "Louis"
    Received: "Amber"

       5 | describe('person objects', () => {
       6 |     test('I am in the family', () => {
    >  7 |         expect(person1.name).toEqual("Louis")
         |                              ^
       8 |     })
       9 |     test('My sister is in the family', () => {
      10 |         expect(person2.name).toEqual("Amber")

      at Object.<anonymous> (family.test.js:7:30)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.178 s

Answer №1

module.exports = character1
module.exports = character2

The module.exports statement assigns an object value to character1, but then overwrites it with character2, thus removing the previous value. To export multiple variables, you should use:

module.exports = {
  character1: character1,
  character2: character2
}

Alternatively, if the variable names match the property names in the object, you can simplify it as suggested by Patrick Evans:

module.exports = {
  character1,
  character2
}

You can also export using:

module.exports.character1 = character1
module.exports.character2 = character2

or a bit shorter:

exports.character1 = character1
exports.character2 = character2

To import named variables, you would do:

const { character1, character2 } = require('./family')

Your test code does not need any modifications.

Answer №2

According to a comment by @Patrick Evans, the solution is simple:

module.exports = {
  person1,
  person2
};

Alternatively, you can export both variables using this method:

exports.person1 = person1;
exports.person2 = person2;

In my opinion, there should generally only be one module.exports = ... statement in each file.

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

"Encountering issues with DefinePlugin when using the combination of Ionic, Angular, Webpack,

I'm trying to incorporate my process.env variable into the webpack Bundle using DefinePlugin. Here's the snippet of code in my webpack config: plugins: [ new webpack.DefinePlugin({ 'process.env': JSON.stringify(process.env) ...

Error message displayed by console when attempting to parse JSON data that is in array

After receiving a simple array as my JSON response: [35,55] The Chrome network inspector confirms that it is valid JSON. However, when attempting to parse the xhr.responseText using JSON.parse, I am confronted with the error: Uncaught SyntaxError: Unexpe ...

Creating a table in HTML using the innerHTML property

document.getElementById("outputDiv").innerHTML = ""; document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>"; for(j=1;j<=10;j++) { document.getElementById("outputDiv").innerHTML += "<td align=center>"+St ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Unable to stop React HTMLAudioElement from playing

In the realm of React, there exists a component that requires a URL input to function. The purpose of this component is to display a button that allows users to control the playback of an audio file. It's worth noting that this particular component is ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

Encountering a problem with serializing forms using jQuery

Currently, I am working on form serialization in order to send the file name to the server. However, I have encountered an issue where the serialization values are empty and I am expecting the file name to be included. Within my form, there is an HTML fil ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...

Troubleshooting the AutoHeight Problem in Slidesjs

My issue revolves around Slidesjs which can be found at . Specifically, I am facing a problem with autoHeight feature not displaying properly in Chrome. Initially, the height of slides shows as 0px but upon clicking to the next slide, it adjusts to the c ...

Angular UI modal on close event

Is there a way to trigger a function after a modal window is closed, regardless of whether it was closed by a button click or clicking on the backdrop? var dialog, options; options = { windowClass: "lightBox" templateUrl: "url to the template", con ...

What is the best method for iterating through files on both Windows and Linux using npm?

When attempting to execute a single command (jshint) on multiple files, I encountered an issue. In my package.json file, I have the following entry: "lint": "jshint *.js **/*.js" Unfortunately, this command fails on Windows. To iterate through multiple f ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Exploring the World of AJAX with CodeIgniter

I've been on the hunt for a solid working example of using AJAX with Codeigniter, but most resources I've found are outdated. As an AJAX beginner, I'm struggling to find up-to-date tutorials. What I'm aiming for is an input form on a w ...

Tips on increasing the width of the 'select' option once the user decides to make a selection

Here's a question for you: I have a <select> box where I set the width to 120px: <select style="width: 120px"> <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option> <option>ABC</option> < ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

Experiencing difficulties in transmitting images/files to API through reactjs and Material UI upload component

Recently, I tackled the task of creating an image upload component by utilizing an upload component from Material UI. While I have experience with this process using a simple HTML file input in the past, I found myself feeling a bit perplexed this time aro ...

I am struggling to successfully upload a video in Laravel

In this section, the Ajax functionality is used to add a video URL to the database. The values for the Video title and description are successfully being saved in the database, but there seems to be an issue with retrieving the URL. <div class="m ...

How can I prevent media controls from appearing in fullscreen mode on Microsoft Edge using CSS?

My video code allows for switching the video into fullscreen mode using custom controls. Here's how it looks: fullScreenButton.addEventListener("click", function() { if (video.requestFullscreen) { video.videoContainer.r ...