如何测试 Mocha/Chai 以验证是否为变量分配了值?

How do I test Mocha/Chai to verify that a variable was assigned a value?

假设我有一个为变量赋值的函数。我该如何在 Mocha/Chai 中进行测试?

除非你正在测试一个对象或者你有某种 getter 你真的无法正确测试因为测试外部状态是不可能的。

以此为例:

x.js

const x = 0

const addX = (num) => x += num
const getX = () => x

x.spec.js

describe('#updateX', () => {
  it('updates x', () => {
    const UPDATE_NUM = 10

    addX(UPDATE_NUM)

    assert.equal(getX(), UPDATE_NUM) // without getX there is no way to get a hold of x
  })
})

classes/objects 如何使这更容易:

something.js

class SomeThing {
  constructor() {
    this.x = 0
  }

  addX(num) {
    this.x =+ num
  }
}

something.spec.js

test('updates x', () => {
  const someThing = new SomeThing(),
        UPDATE_NUM = 5

  someThing.addX(UPDATE_NUM)

  assert.equal(someThing.x, UPDATE_NUM)
})

最佳方案

使用纯函数!

const addX = (x, num) => x + num

现在您不依赖外部状态,测试就像

一样简单
it('adds num to x', () => {
  const UPDATE_NUM = 10

  assert.equal(addX(0, UPDATE_NUM), UPDATE_NUM)
})