测试框架-Mocha

  • arrom
  • 更新于 2022-11-25 14:46
  • 阅读 1566

mocha是一款运行在nodejs上的测试框架,支持同步和异步测试,同时还支持TDD,BDD等多种测试风格。

mocha是什么

一款运行在nodejs上的测试框架,支持同步和异步测试,同时还支持TDD,BDD等多种测试风格

使用mocha写的测试用例

import { expect } from "chai";
import { ethers } from "hardhat";

describe("Adoption", function() {

    async function getInitAdopt() {
        const Adoption= await ethers.getContractFactory("Adoption");
        const adoption = await Adoption.deploy();
        return { adoption };
    }

    describe("adopt", () =>{
       it("Is there a petid equal to 9",async () => {
           const {adoption} = await getInitAdopt();
           adoption.adopt(9).then((data) => {
                expect(data).to.equal(9);
           });

       });
    });

    describe("getAdopters" ,  () => {

        it("Owner of petId 9 should be record", async () => {
            const {adoption} = await getInitAdopt();
            adoption.adopters(9).then((data) => {
                expect(data).to.equal(adoption.address);
            });
        });
    });

});

核心函数:describe和it

describe->函数我们称为测试套件,它的核心功能是来描述测试的流程 it->函数我们称为一个测试单元,它的功能是来执行具体的测试用例

钩子函数

describe('检查:函数执行', function () {
  before(function() {
    console.log('😁before钩子触发');
  });
  describe('测试:正常流', function() {
    it('类型返回: [object JSON]', function (done) {
      setTimeout(() => {
        assert.equal(函数(JSON), '[object JSON]');
        done();
      }, 1000);
    });
    it('类型返回: [object Number]', function() {
      assert.equal(函数(1), '[object Number]');
    });
  });
  describe('测试:异常流', function() {
    it('类型返回: [object Undefined]', function() {
      assert.equal(函数(undefined), '[object Undefined]');
    });
  });
  after(function() {
    console.log('😭after钩子触发');
  });
});

before: 在执行测试套件之前触发该钩子 after:在测试套件执行结束后触发该钩子 beforeEach:在每个测试单元执行之前触发该钩子 afterEach:在每个测试单元执行结束后触发该钩子

支持异步

it('类型返回: [object JSON]', function (done) {
  setTimeout(() => {
    assert.equal(getTag(JSON), '[object JSON]');
    done();
  }, 1000);
});

mocha支持两种方式的异步代码,一种是回调函数直接返回一个Promise,一种是支持在回调函数中传参数done,手动调用done函数来结束用例

点赞 1
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
arrom
arrom
江湖只有他的大名,没有他的介绍。