用过Rhino Mocks后大家一定对它印象深刻,用它来做单元测试的case相当的省事。今天咱们同样来介绍一款Mock工具:JsMockito,用它能轻松的制作JavaScript程序的单元测试case。
JsMockito的运行还依赖另外一款开源的JS工具:JsHamcrest,我们可以通过如下代码来搭建测试环境:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Test JavaScript Mock</title> <script src="jshamcrest.js" language="javascript" type="text/javascript"></script> <script src="jsmockito.js" language="javascript" type="text/javascript"></script> <script language="javascript" type="text/javascript"> var mockFunc = JsMockito.mockFunction(); JsMockito.when(mockFunc)('jim').thenReturn('hello jim'); alert(mockFunc('jim')); </script> </head> <body> </body> </html>
var mockArray = JsMockito.mock(Array); JsMockito.when(mockArray).slice(10).thenReturn('^__^'); alert(mockArray.slice(10)); //结果是: ^__^
bob = { FullName: 'bob ling', Introduce: function () { return 'im bob'; } }; var mockIntroduce = JsMockito.mockFunction(); JsMockito.when(mockIntroduce)().thenReturn("it's ok!"); bob.Introduce = mockIntroduce; alert(bob.Introduce()); //结果是: it's ok
var mockBob = JsMockito.mock(bob); mockBob.FullName = 'Bruce Lee'; alert(mockBob.FullName);//结果是:Bruce Lee
var mockFunction = JsMockito.mockFunction(); JsMockito.when(mockFunction)(JsHamcrest.Matchers.lessThan(10) && JsHamcrest.Matchers.greaterThan(5), JsHamcrest.Matchers.anything()).thenReturn('this value must belong 5 to 10'); alert(mockFunction(6, null)); //this value must belong 5 to 10 alert(mockFunction(2, null));//undefined
context1 = {}; context2 = {}; var mockFunc = JsMockito.mockFunction(); JsMockito.when(mockFunc).call(context1).thenReturn('this method was called by context'); alert(mockFunc.apply(context1)); //this method was called by context alert(mockFunc.apply(context2)); //undefined alert(mockFunc.call(context1)); //this method was called by context alert(mockFunc.call(context2)); //undefined