简体   繁体   English

Babel const可防止突变?

[英]Babel const prevents mutation?

I'm writing tests in ES6 syntax powered by Babel, and I'm using Jest to run the tests. 我正在使用由Babel提供支持的ES6语法编写测试,并且正在使用Jest运行测试。 Here my test code: 这是我的测试代码:

test('case: response body contains a user, should update sessionData', () => {
  // current user info in the session
  const currentUserInfo = {
    firstName: 'User1',
    lastName: 'Old Info'
  }

  const mockSessionData = createSessionHelper(
    {
      data: {
        user: currentUserInfo
      }
    },
    mockLogger
  )

  // new user info in the body
  const newUserInfo = {
    firstName: 'User2',
    lastName: 'New Info'
  }

  const body = {
    user: newUserInfo
  }

  const result = handleSuccess({
    req: {
      sessionData: mockSessionData
    },
    body
  })

  expect(result.status).toBe(DEFAULT_SUCCESS_STATUS)
  expect(result.body).toEqual(body)
  expect(mockSessionData.get('user')).toEqual(newUserInfo)
})

As you can see, I'm using the same objects both to use as parameters to the functions I'm testing and, to match the result with my expectation. 如您所见,我正在使用相同的对象,将它们用作我正在测试的函数的参数,并将结果与​​期望相匹配。

I'm assuming here that these functions should not mutate those parameters. 我在这里假设这些功能不应使这些参数发生变化。 Is this assumption true, though? 这个假设是真的吗?

By using Babel const , will my data remain the same, or should I still use Object.freeze() ? 通过使用Babel const ,我的数据将保持不变,还是我仍应使用Object.freeze()

As the reference says, 参考文献所述

The value of a constant cannot change through re-assignment, and it can't be redeclared. 常量的值不能通过重新分配而更改,也不能重新声明。

mockSessionData cannot be re-assigned. 无法重新分配mockSessionData const can't and shouldn't prevent an object that mockSessionData holds a reference to from being modified. const不能也不应阻止对mockSessionData持有引用的对象进行修改。 Object.freeze may be used if the object shouldn't be changed. 如果不应更改对象,则可以使用Object.freeze

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM