让我们说我有一个为变量赋值的函数。我如何在Mocha / Chai中进行测试?
答案 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)
})