美文网首页前端技术
令人愉快的测试 Jest

令人愉快的测试 Jest

作者: 一俢 | 来源:发表于2019-03-18 09:33 被阅读18次

Jest 是由 Facebook 出品的 JavaScript 测试框架,官方声称通过它可以完成“令人愉快的 JavaScript 测试”。

在 TDD(Test-Driven Development)开发方法中,编写测试代码尤为重要,Jest 让这一切变得更佳的简单。

快速入门

安装:

  • yarn: yarn add --dev jest
  • or npm: npm install --save-dev jest

被测试的模块 hello.js

function hello() {
    return 'Hello world!';
}

module.exports = hello;

创建测试文件 hello.test.js

const hello = require('./hello');

test('hello', () => {
    expect(hello()).toBe('Hello world!');
});

配置 package.json

{
    //...
    "scripts": {
        "test": "jest",
        "coverage": "jest --coverage"
    }
    //...
}

运行 yarn test 开始测试:

PASS ./hello.test.js

生成覆盖率:

jest --coverage

以上就是你的第一个 Jest 单元测试。

Babel

通过安装 babel-jestregenerator-runtime 可以让 Jest 支持 ES6 的新语法:

yarn add --dev babel-jest babel-core regenerator-runtime

配置 .babelrc

{
    "presets": [
        "es2015",
        "stage-2"
    ]
}

相关文章

网友评论

    本文标题:令人愉快的测试 Jest

    本文链接:https://www.haomeiwen.com/subject/uewmmqtx.html