{"content":{"title":"测试框架-Mocha","body":"mocha是什么\r\n--\r\n一款运行在nodejs上的测试框架，支持同步和异步测试，同时还支持TDD，BDD等多种测试风格\r\n\r\n使用mocha写的测试用例\r\n---\r\n\r\n```\r\nimport { expect } from \"chai\";\r\nimport { ethers } from \"hardhat\";\r\n\r\ndescribe(\"Adoption\", function() {\r\n\r\n    async function getInitAdopt() {\r\n        const Adoption= await ethers.getContractFactory(\"Adoption\");\r\n        const adoption = await Adoption.deploy();\r\n        return { adoption };\r\n    }\r\n   \r\n    describe(\"adopt\", () =>{\r\n       it(\"Is there a petid equal to 9\",async () => {\r\n           const {adoption} = await getInitAdopt();\r\n           adoption.adopt(9).then((data) => {\r\n                expect(data).to.equal(9);\r\n           });\r\n           \r\n       });\r\n    });\r\n\r\n    describe(\"getAdopters\" ,  () => {\r\n\r\n        it(\"Owner of petId 9 should be record\", async () => {\r\n            const {adoption} = await getInitAdopt();\r\n            adoption.adopters(9).then((data) => {\r\n                expect(data).to.equal(adoption.address);\r\n            });\r\n        });\r\n    });\r\n    \r\n});\r\n\r\n```\r\n核心函数：describe和it\r\n--\r\ndescribe->函数我们称为测试套件，它的核心功能是来描述测试的流程\r\nit->函数我们称为一个测试单元，它的功能是来执行具体的测试用例\r\n\r\n钩子函数\r\n--\r\n```\r\ndescribe('检查：函数执行', function () {\r\n  before(function() {\r\n    console.log('😁before钩子触发');\r\n  });\r\n  describe('测试：正常流', function() {\r\n    it('类型返回： [object JSON]', function (done) {\r\n      setTimeout(() => {\r\n        assert.equal(函数(JSON), '[object JSON]');\r\n        done();\r\n      }, 1000);\r\n    });\r\n    it('类型返回： [object Number]', function() {\r\n      assert.equal(函数(1), '[object Number]');\r\n    });\r\n  });\r\n  describe('测试：异常流', function() {\r\n    it('类型返回： [object Undefined]', function() {\r\n      assert.equal(函数(undefined), '[object Undefined]');\r\n    });\r\n  });\r\n  after(function() {\r\n    console.log('😭after钩子触发');\r\n  });\r\n});\r\n\r\n```\r\nbefore: 在执行测试套件之前触发该钩子\r\nafter：在测试套件执行结束后触发该钩子\r\nbeforeEach：在每个测试单元执行之前触发该钩子\r\nafterEach：在每个测试单元执行结束后触发该钩子\r\n\r\n支持异步\r\n--\r\n```\r\nit('类型返回： [object JSON]', function (done) {\r\n  setTimeout(() => {\r\n    assert.equal(getTag(JSON), '[object JSON]');\r\n    done();\r\n  }, 1000);\r\n});\r\n```\r\nmocha支持两种方式的异步代码，一种是回调函数直接返回一个Promise，一种是支持在回调函数中传参数done，手动调用done函数来结束用例"},"author":{"user":"https://learnblockchain.cn/people/5348","address":null},"history":null,"timestamp":1669358817,"version":1}