node.js - Mocha 单元测试: where to create variables

标签 node.js unit-testing mocha.js

我刚刚第一次进行单元测试。使用 Node 中的 Mocha 作为测试框架。我遇到的所有示例都在 it() 内创建变量。它们是在 it() 内部还是外部创建的,这很重要吗?例如,如果我在 describe() 中有多个 it(),并且我需要在所有 it() 中使用相同的模拟数据。如果可能的话,我不想重复地重新创建相同的变量。

describe ('MyClass', function () {
    let myObj = new MyObj // Mock data here
    it ('Should be...', function () {
        ....
    })
    it ('Should be...', function () {
        ....
    })
    ...
})

最佳答案

将变量存在于各个 it block 之外是完全可以接受的,但根据您的用例,它可能不合适。

对于您不希望更改的对象,Object.freeze 是一个选项:const myObj = Object.freeze(new MyObj)

如果您希望测试更改对象,则应使用 beforeEach 来确保它们恢复到正确的状态;这将防止您的 it block 相互污染,并避免不愉快的调试过程。

例如:

describe('MyClass', function () {
  let myObj

  beforEach(() => {
    myObj = new MyObj()
  })

  it('changes myObj', () => {
    changeProp(myObj.sum)
    expect(myObj.sum).toEqual(4)
  })

  it('depends on myObj being the same', () => {
    expect(myObj.sum).toEqual(2)
  })
})

或者,您可以避开粗箭头语法并依赖 mocha 中 block 之间的共享上下文:

beforeEach(function () {
  this.myObj = new MyObj()
})

it('changes myObj', function () {
  addTwo(this.myObj.sum)
  expect(this.myObj.sum).toEqual(4)
})

it('depends on myObj being the same', function () {
  expect(this.myObj.sum).toEqual(2)
})

关于node.js - Mocha 单元测试: where to create variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45766878/

相关文章:

javascript - 单元测试未定义不是一个对象(评估 'this.groups.map' )

node.js - 需要来自 Electron 的原生 C++ 插件的问题

python - 基于输入参数模拟python函数

javascript - Node.js 中的路由模块出现 `Cannot GET/en/first` 错误

java - 如何模拟对从 protected 资源继承的接口(interface)的调用

angularjs - 使用 sinon、mocha、chai 进行 Angular 测试

javascript - 如何使用 sinon 正确模拟 ES6 类

node.js - "node --debug"和 "node --debug-brk"无效

javascript - 没有 node.js 服务器的客户端 socket.io

javascript - 我正在尝试通过 Express 为我的 React 应用程序提供服务,为什么会收到 404 错误?