Built in assertion module – Eternal Night https://www.shuijingwanwq.com There is no problem not worth solving, and no technology not worth learning! Thu, 21 May 2026 12:38:31 +0000 en-US hourly 1 https://wordpress.org/?v=7.0 Run test cases based on Mocha, using the assertion library Chai https://www.shuijingwanwq.com/en/2023/02/16/12763/ https://www.shuijingwanwq.com/en/2023/02/16/12763/#respond Thu, 16 Feb 2023 13:20:31 +0000 https://www.shuijingwanwq.com/?p=12763 浏览量: 14

1. Reference: In Refactoring: Improve the Design of Existing Code (2nd Edition), run test cases based on Mocha.

2. MOCHA allows you to use any of the assertion libraries you want. In the above example, we used Node.js’s built-in assertion module. Schedule to use assertion library Chai.

3. Reference:https://mochajs.org/#assertions. The assertion library Chai supports expect(), assert() and should style assertions. as shown in Figure 1

参考:https://mochajs.org/#assertions 。断言库 Chai支持 expect()、assert() 和 should 风格的断言

Figure 1

4. Execute the command: npm install chai , install chai. as shown in Figure 2

执行命令:npm install chai ,安装 Chai

Figure 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. Edit the test file 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. Run the test and pass the test. as shown in Figure 3

运行测试,测试通过

Figure 3


PS E:\wwwroot\refactoring> npm test

> test
> mocha



  province
    √ shortfall
    √ profit


  2 passing (13ms)



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