前端单元测试

JavaScript测试框架Mocha & 断言库chai

TDD=Testing-Driven Development

Chai Assertion Library MOCHA simple, flexible, fun MOCHA中文网站 简单, 灵活, 有趣

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. 是一个功能丰富的javascript测试框架,运行在node.js和浏览器中,使异步测试变得简单有趣。

GitHub repository

Example 示例代码

文件结构:

index.html
problem.js
tests.js

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mocha & chai Tests</title>
    <!-- <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" /> -->
    <link href="mocha2.2.5.css" rel="stylesheet" />
</head>
<body>
    <div id="mocha"></div>
    <!-- <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script> -->
    <!-- <script src="https://cdn.rawgit.com/chaijs/chai/3.5.0/chai.js"></script> -->
    <!-- <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script> -->

    <script src="expect0.3.1index.js"></script>
    <script src="chai3.5.0.js" type="text/javascript"></script>
    <script src="mocha2.2.5.js"></script>

    <script src="problem.js"></script>
    <script>
        const mocha = window.mocha;
        mocha.setup('bdd');
    </script>
    <script src="tests.js"></script>
    <script>
        mocha.checkLeaks();
        mocha.run();
    </script>
</body>
</html>

problem.js

// farenheit to celcius
// [23,140,212,41] => [-5,60,100,5]
// (32*F-32)*5/9=0c

function getCelcius(farenheit) {
    return farenheit.map(value => (value-32) * 5.9)

}

tests.js

const chai = window.chai
const expect = chai.expect

describe('getCelcius', () => {
    it('should convert farenheit to celcius for all values in an array', () => {
        expect(getCelcius([23,140,212,41])).to.deep.equal([-5,60,100,5])
    })
})

在浏览器打开运行index.html

test failure

修正代码: 5.9 -> 5/9

problem.js

// farenheit to celcius
// [23,140,212,41] => [-5,60,100,5]
// (32*F-32)*5/9=0c

function getCelcius(farenheit) {
    return farenheit.map(value => (value-32) * 5/9)

}

刷新浏览器

test success

输入更多用例

const chai = window.chai
const expect = chai.expect

describe('getCelcius', () => {
    it('should convert farenheit to celcius for all values in an array', () => {
        expect(getCelcius([23,140,212,41])).to.deep.equal([-5,60,100,5])
        expect(getCelcius([-58,-22,-4,14])).to.deep.equal([-50,-30,-20,-10])
    })
})

运行

test success

来源:Write a Unit Test for JavaScript (super simple!)

Copyright © 德和居 2021 粤ICP备20069867号 在CC-BY-NC-SA 4.0协议下授权使用,除非另有说明 all right reserved,powered by Gitbook本文修订时间: 2021-03-29 17:48:00

results matching ""

    No results matching ""

    results matching ""

      No results matching ""