内置断言模块 – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Thu, 16 Feb 2023 13:20:31 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 基于 Mocha 运行测试用例,使用断言库 Chai https://www.shuijingwanwq.com/2023/02/16/7427/ https://www.shuijingwanwq.com/2023/02/16/7427/#respond Thu, 16 Feb 2023 13:20:31 +0000 https://www.shuijingwanwq.com/?p=7427 浏览量: 103 1、参考:在 重构:改善既有代码的设计 (第2版) 中,基于 Mocha 运行测试用例 。 2、Mocha 允许您使用任何您想要的断言库。 在上面的例子中,我们使用了 Node.js 的内置断言模块。计划切换为使用断言库 Chai。 3、参考:https://mochajs.org/#assertions 。断言库 Chai支持 expect()、assert() 和 should 风格的断言。如图1
参考:https://mochajs.org/#assertions 。断言库 Chai支持 expect()、assert() 和 should 风格的断言

图1

4、执行命令:npm install chai ,安装 Chai。如图2
执行命令:npm install chai ,安装 Chai

图2



PS E:\wwwroot\refactoring> npm install chai

added 8 packages, and audited 86 packages in 11s

20 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities


5、编辑测试文件 test/province.js


import {Province} from '../4/modules/province.js';
import chai from 'chai';

function sampleProvinceData() {
    return {
        name: "Asia",
        producers: [{name: "Byzantium", cost: 10, production: 9}, {
            name: "Attalia",
            cost: 12,
            production: 10
        }, {name: "Sinope", cost: 10, production: 6},],
        demand: 30,
        price: 20
    };
}

var expect = chai.expect;
describe('province', function() {
    it('shortfall', function() {
        const asia = new Province(sampleProvinceData());
        expect(asia.shortfall).equal(5);
    });
    it('profit', function() {
        const asia = new Province(sampleProvinceData());
        expect(asia.profit).equal(230);
    });
});


6、运行测试,测试通过。如图3
运行测试,测试通过

图3



PS E:\wwwroot\refactoring> npm test

> test
> mocha



  province
    √ shortfall
    √ profit


  2 passing (13ms)



]]>
https://www.shuijingwanwq.com/2023/02/16/7427/feed/ 0