Mocha Chai-编写和运行测试
在本教程中,我们将编写一些JavaScript代码,然后使用Mocha和Chai对其进行测试。
在之前的教程Mocha Chai-介绍和设置Mocha以进行测试中,我们学习了如何安装Mocha,然后对其进行设置以进行测试。
随时检查一下。
创建一个Box类进行测试
让我们继续在项目文件夹中创建js
目录。
然后在js目录中创建Box.js
文件,并编写以下代码。
var Box = function(length, width, height) { this.length = length; this.width = width; this.height = height; }; Box.prototype.getVolume = function() { return this.length * this.width * this.height; }; module.exports = Box;
说明
我们在上面的代码中创建Box类。
在初始化Box时,我们会将Box的长度,宽度和高度传递给构造函数。
要获取Box的体积,我们可以调用getVolume
方法。
在最后一行中,我们正在导出Box。
因此,在测试文件中,我们将需要此Box。
测试代码
在test
目录中以Box.test.js
命名创建一个新文件。
我们将在该文件中编写测试。
如果现在在终端中运行npm run test
,我们将得到以下输出。
$npm run test > [email protected] test /Users//Documents/GitHub/mocha-chai-project > mocha || true 0 passing (2ms)
注意!由于我们在Box.test.js文件中没有任何测试,因此在输出中获得0通过。
需要Chai模块的断言
在Box.test.js文件内部,需要从Chai模块中进行断言。
Chai的assert
与Node.jsassert
类似,但具有一些额外的函数。
接下来,我们将在测试文件中需要Box
模块。
此时,我们的测试文件将如下所示。
var assert = require('Chai').assert; var Box = require('../js/Box');
注意!我们不在上面的var Box = require('../js/Box');
行中使用扩展名" .js"。
它会自动推断出来。
描述测试
我们使用describe
来对相似的测试进行分组,并且需要两个参数。
第一个描述测试组,第二个描述一个函数,其中编写一些测试。
因此,让我们通过在Box.test.js文件中编写以下代码来描述我们的测试。
describe('Testing Box', function() { //some code goes here... })
用it
测试
我们使用" it"方法编写测试。
它需要两个参数。
第一个描述测试,第二个描述一个函数,我们其中编写测试。
因此,让我们断言使用Box类创建的对象是否是该类的实例。
为此,我们将使用" instanceOf()"方法。
它有两个参数。
第一个是对象,第二个是构造函数。
describe('Testing Box', function() { it('should assert obj is instance of Box', function() { var obj = new Box(10, 20, 30); assert.instanceOf(obj, Box); }) })
如果现在运行测试,将得到以下输出。
$npm run test > [email protected] test /Users//Documents/GitHub/mocha-chai-project > mocha || true Testing Box ✓ should assert obj is instance of Box 1 passing (9ms)
因此,我们的测试通过了。
再次测试以检查音量
我们可以使用" it"编写另一个测试来检查Box类的" getVolume"方法。
为了匹配该值,我们将使用带有两个参数的"等于"方法。
第一个是实际值,第二个是期望值。
为了测试getVolume
方法,在创建Box类的对象时,我们将传递10、20和30作为长度,宽度和高度。
预期结果为" 10 x 20 x 30 = 6000"。
因此,如果实际值和期望值匹配,则测试将通过。
我们的下一个代码将如下所示。
it('should assert volume of the box to be 6000', function() { //create an object var obj = new Box(10, 20, 30); //now assert the volume assert.equal(obj.getVolume(), 6000); })
最终测试代码
现在,我们的Box.test.js文件将如下所示。
var assert = require('Chai').assert; var Box = require('../js/Box'); describe('Testing Box', function() { it('should assert obj is instance of Box', function() { var obj = new Box(10, 20, 30); assert.instanceOf(obj, Box); }) it('should assert volume of the box to be 6000', function() { //create an object var obj = new Box(10, 20, 30); //now assert the volume assert.equal(obj.getVolume(), 6000); }) })
在运行测试时,我们将获得以下输出。
$npm run test > [email protected] test /Users//Documents/GitHub/mocha-chai-project > mocha || true Testing Box ✓ should assert obj is instance of Box ✓ should assert volume of the box to be 6000 2 passing (10ms)
因此,我们可以看到两个测试都通过了。