我是否错误地导出了我的对象? JS 新手不明白为什么测试失败

Am I exporting my objects incorrectly? new to JS don't understand why test is failing

我是新手Javascript,我的老师从对象和测试驱动开发开始。

这是我的代码和附带的测试失败了,我不太清楚为什么。当我只有第一个对象和第一个测试时它起作用了,但是当我添加第二个对象时它失败了。

主要:

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

module.exports = person1
module.exports = person2

测试代码:

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")
    })
})

测试结果:

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

正如评论 @Patrick Evans 中所述,您只需要:

module.exports = {
  person1,
  person2
};

或者,您可以像这样导出两个变量:

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

我想,文件中一般应该只有1条module.exports = ...语句。

module.exports = person1
module.exports = person2

module.exports是一个对象,所以你上面做的就是把对象值赋给person1,然后把对象值覆盖给person2,所以Louis就没了。

如果你想导出多个变量,你会这样做:

module.exports = {
  person1: person1,
  person2: person2
}

或者如果对象 属性 名称与变量名称相同,您可以缩短它,如 Patrick Evans 在他的回答中所述:

module.exports = {
  person1,
  person2
}

您还可以使用以下方式导出:

module.exports.person1 = person1
module.exports.person2 = person2

或略微缩短为:

exports.person1 = person1
exports.person2 = person2

要进行命名导入,您可以这样做:

const { person1, person2 } = require('./family')

否则您不需要更改测试代码。