I am new to learning Javascript and my teacher is starting with objects and test driven development.
This is my code and the accompanying tests which are failing and I am not quite sure why. When I only had the first object and the first test it worked but when I added the second one it is failing.
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
module.exports = person1
module.exports = person2
module.exports is an object, so what you're doing above is assigning the object value to person1 and then overwriting the object value to person2, so Louis is gone.
If you want to export multiple variables, you would do:
module.exports = {
person1: person1,
person2: person2
}
Or if the object property name is the same as the variable name, you could shorten it as Patrick Evans stated in his answer:
module.exports = {
person1,
person2
}
You can also export using:
module.exports.person1 = person1
module.exports.person2 = person2
or shortened slightly to:
exports.person1 = person1
exports.person2 = person2
To do a named import, you would do:
const { person1, person2 } = require('./family')
You wouldn't need to change your test code otherwise.