[Node.js基础]学习②0--异步测试mocha

http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014723007105817ff3d8fae5b9491a88982aa1655e66be000

package.json

{
  "name": "mocha-async-test",
  "version": "1.0.0",
  "description": "Mocha async test",
  "main": "hello.js",
  "scripts": {
    "test": "mocha"
  },
  "keywords": [
    "mocha",
    "test",
    "async"
  ],
  "author": "Michael Liao",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/michaelliao/learn-javascript.git"
  },
  "dependencies": {
    "mz": "2.4.0"
  },
  "devDependencies": {
    "mocha": "3.0.2"
  }
}

hello.js

// hello.js
console.log('init hello.js...');

const fs = require('mz/fs');

// a simple async function:
module.exports = async () => {
    let expression = await fs.readFile('./data.txt', 'utf-8');
    let fn = new Function('return ' + expression);
    let r = fn();
    console.log(`Calculate: ${expression} = ${r}`);
    return r;
};

data.txt

1 + (2 + 4) * (9 - 2) / 3

test目录

await-test.js

const assert = require('assert');

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

describe('#async hello', () => {
    describe('#asyncCalculate()', () => {
        // function(done) {}
        it('#async with done', (done) => {
            (async function () {
                try {
                    let r = await hello();
                    assert.strictEqual(r, 15);
                    done();
                } catch (err) {
                    done(err);
                }
            })();
        });

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

        it('#sync function', () => {
            assert(true);
        });
    });
});

[Node.js基础]学习②0--异步测试mocha_第1张图片
Paste_Image.png

你可能感兴趣的:([Node.js基础]学习②0--异步测试mocha)