Coder Social home page Coder Social logo

js-test's People

Contributors

ly2011 avatar

Watchers

James Cloos avatar

js-test's Issues

mocha

mocha

mocha 是JavaScript中一种单元测试框架,既可以在浏览器环境下运行,也可以在Node.js环境下运行。

mocha的特点主要有:

  1. 既可以测试简单的JavaScript函数,又可以测试异步代码,因为异步是JavaScript的特征之一;
  2. 可以自动运行所有测试,也可以只运行特定的测试;
  3. 可以支持 beforeafterbeforeEachafterEach 来编写代码。

测试脚本的写法

通常,测试的脚本与要测试的源码脚本同名,但是后缀名为 .test.js (表示测试)或者 .spec.js (表示规格)

测试脚本里面应该包括一个或多个 describe 块,每个 describe 块应该包括一个或多个 it 块。

describe 块称为 "测试套件"(test suite),表示一组相关的测试。它是一个函数,第一个参数是测试套件的名称,第二个参数是一个实际执行的函数。

it 块称为 "测试用例"(test case),表示一个单独的测试,是测试的最小单位。它也是一个函数,第一个参数是测试用例的名称,第二个参数是一个实际执行的函数。

注意

mocha 默认只执行 test 子目录下面第一层的测试用例,不会执行更下层的用例。
为了改变这种行为,就必须加上 --recursive 参数,这时 test 子目录下面所有的测试用例----不管在哪一层----都会执行。

{
  ...

  "scripts": {
    "test": "mocha --recursive"
  }
  ...
}

运行测试

运行mocha测试的方法有三种

  1. 打开命令行提示符,切换到项目(hello-test)目录,然后执行命令:
C:\hello-test> node_modules\mocha\bin\mocha
  1. package.json 中添加npm命令:
{
  ...

  "scripts": {
    "test": "mocha"
  }
  ...
}

然后再 hello-test 目录下执行命令:

C:\hello-test>npm test
  1. 在VS Code 中创建配置文件 .vscode/launch.json,然后编写两个配置选项:
{
  // Use IntelliSense to learn about possible Node.js debug attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [{
      "name": "Run",
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/hello.js",
      "stopOnEntry": false,
      "args": [],
      "cwd": "${workspaceRoot}",
      "preLaunchTask": null,
      "runtimeExecutable": null,
      "runtimeArgs": [
        "--nolazy"
      ],
      "env": {
        "NODE_ENV": "development"
      },
      "console": "externalTerminal",
      "sourceMaps": false,
      "outFiles": []
    }, {
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
      "args": [
        "-u",
        "tdd",
        "--timeout",
        "999999",
        "--colors",
        "${workspaceRoot}/test"
      ],
      "internalConsoleOptions": "openOnSessionStart"
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${file}"
    }
  ]
}

注意第一个配置选项 Run 是正常执行一个.js文件,第二个配置选项 Mocha Tests 我们填入 "program": "${workspaceRoot}/node_modules/mocha/bin/mocha",这样,就可以在VS Code中打开Debug面板,选择 Mocha Tests,运行,即可在Console面板中看到测试结果。

测试异步函数

测试同步函数

如果要测试同步函数,我们传人 无参数函数 即可:

it('#test sync function', () => {
// TODO:
})

测试异步函数

  • 方法一

如果要测试异步函数,我们要传人的函数需要带一个参数,通常命名为 done

const fs = require('mz/fs')
it('#test async function', (done) => {
  fs.readFile('filepath', (err,data) => {
  if (err) {
      done(err)
    } else {
      done()
    }
  })
})

测试异步函数需要在函数内部手动调用 done() 表示测试成功,done(err) 表示测试出错。

  • 方法二(借助es7的async编写的函数):
it('#async with done', (done) => {
  (async () => {
    try{
      const r = await hello()
      assert.strictEqual(r, 15)
      done()
    } catch(err) {
      done(err)
    }
  })
})
  • 方法三(直接把async函数当成同步函数来测试):(推荐)

it('#async function', async () => {
  const r = await hello()
  assert.strictEqual(r, 15)
})

HTTP测试

借助 supertest 测试模块

通配符

命令行制定测试脚本时,可以使用通配符,同时指定多个文件。

{
  ...

  "scripts": {
    "test": "mocha test/unit/**/*.js"
  }
  ...
}

命令行参数

  • --recursive

  • --help, -h

--help-h 参数,用来查看Mocha的所有命令行参数。

  • --reporter, -R

--reporter 参数用来指定测试报告的格式,默认是 spec 格式。

  • --growl, -G

打开 --growl 参数,就会将测试结果在桌面显示

  • --watch, -w

--watch 参数用来监控指定的测试脚本。只要测试脚本有变化,就会自动运行 Mocha 。

  • --bail, -b

--bail 参数指定只要有一个测试用例没有通过,就停止执行后面的测试用例。

  • --grep, -g

--grep 参数用于搜索测试用例的名称(即it块的第一个参数),然后只执行匹配的测试用例。

$ mocha --grep "1 加 1"
  • --invert, -i
    --invert 参数表示只运行不符合条件的测试脚本,必须与 --grep 参数配合使用。
mocha --grep "1 加 1" --invert

测试用例管理

大型项目有很多测试用例。有时,我们希望只运行其中的几个,这时可以用 only 方法。describe 块和 it 块都允许调用 only 方法,表示只运行某个测试套件或测试用例。

  • only

it.only('1 加 1应该等于 2', async() => {
  const r = await add(1, 2)
  asset.strictEqual(r, 2)
})
it('任何数加0应该等于自身', async () => {
  const r = await add(1, 0)
  asset.strictEqual(r, 1)
});

上面代码中,只有带有 only 方法的测试用例会运行。

此外还有 skip 方法,表示跳过指定的测试套件或测试用例。

it.skip('任何数加0应该等于自身', async () => {
  const r = await add(1, 0)
  asset.strictEqual(r, 1)
});

上面代码的这个测试用例不会执行。

浏览器测试

除了在命令行运行外,mocha 还可以在浏览器运行。

  1. 首先,使用 mocha init 命令在指定目录生成初始化文件
$ mocha init test

运行上面命令后,就会在 test 目录下生成 index.html 文件,以及配套的脚本和样式表。

<!DOCTYPE html>
<html>
  <body>
    <h1>Unit.js tests in the browser with Mocha</h1>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script>
      mocha.setup('bdd');
    </script>
    <script src="tests.js"></script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.