没有不值得去解决的问题,也没有不值得去学习的技术!

Run Test Cases With Mocha and the Chai Assertion Library

Reference: https://mochajs.org/#assertions . The Chai assertion library supports expect(), assert(), and should style assertions

1. Reference: In Refactoring: Improving the Design of Existing Code (2nd Edition), test cases are run using Mocha.

2. Mocha allows you to use any assertion library you want. In the example above, we used Node.js’s built-in assert module. I plan to switch to using the Chai assertion library.

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

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

4. Run the command: npm install chai to install Chai. See Figure 2.

Run the command: npm install chai to install Chai
Figure 2
Plaintext

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

JavaScript

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 tests; the tests pass. See Figure 3.

Run the tests; the tests pass
Figure 3
Plaintext

PS E:\wwwroot\refactoring> npm test

> test
> mocha



  province
    √ shortfall
    √ profit


  2 passing (13ms)


关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系