我正在尝试为使用 Appcelerator titanium 开发的移动应用程序编写单元测试。我正在尝试使用 TiUnit 和 Jasmine 对其进行单元测试。
我的方法之一使用 String.format()
。由于 String.format()
未在 Javascript 中定义,我该如何对该方法进行单元测试?
function MyMethod(_flag, _myProperty, _propertyValue) {
if(_flag) {
_myProperty = String.format('The value :', _propertyValue);
}
}
是否可以模拟这个?或者我是否可以将 format() 添加到 jasmine 的 String 原型(prototype)中,以便每当它遇到要测试的 .js 中的 format() 时,它会执行我将在测试套件中定义的 format()?
最佳答案
解决此问题的一种方法是将其设为 pure function .
以这个小改动为例:
function MyMethod(_flag, _myProperty, _propertyValue, formatFunction) {
if(_flag) {
_myProperty = formatFunction('The value :', _propertyValue);
}
}
现在 MyMethod
不依赖于函数外部的任何内容。这允许您使用任何您想要的字符串格式化程序,在您的情况下是模拟的。
在您的测试中,您现在可以执行如下操作:
it('should format the string', () => {
const mockFormatter = () => {/*do the mock operation of your choosing here*/}
const formattedString = MyMethod(yourFlag, yourProperty, yourPropertyValue, mockFormatter)
assert(formattedString, expectedOutput)
})
这允许您不必操作全局 String 对象/原型(prototype),这可能会对其他地方产生影响。相反,您创建一个与格式化程序无关的函数并且能够轻松模拟它。
最后,既然我已经希望为您的原始问题提供一条前进的道路,我很好奇您为什么要模拟格式化程序?这似乎是您总是想要验证的事情,并且这样做没有任何坏处。对我来说,这可能会导致非常深入且经常对测试进行迂腐的讨论,这已经足够作为单元测试了。它不是“纯粹的”,但就副作用而言,没有任何副作用,您正在测试围绕数据操作的一些基本期望。
我认为模拟 String.format()
会给测试带来不必要的复杂性,而不会真正提高代码的可信度。
**编辑:我假设 String.format()
是一个我没听说过的 JS 函数,但事实似乎并非如此。
为了实现您的目标,并避免完全模拟的需要,我认为您应该通过字符串文字或连接使用字符串插值。
看这里:
function MyMethod(_flag, _myProperty, _propertyValue) {
if(_flag) {
_myProperty = `The value : ${_propertyValue}`; // option 1 uses interpolation
// _myProperty = 'The value : ' + _propertyValue; // option 2 uses concatenation
}
}
关于javascript - Jasmine 中的模拟字符串.格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866653/