如何测试Mocha / Chai以验证变量是否已赋值?

时间:2017-01-24 02:33:05

标签: javascript testing mocha chai

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

1 个答案:

答案 0 :(得分:1)

除非您正在测试某个对象,或者您有某种类型的吸气剂,否则您无法正常测试,因为测试外部状态是不可能的。

以此为例:

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

类/对象如何使这更容易:

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