Skip to content

实现简易EventBus:2021-7-11 #26

@jsonz1993

Description

@jsonz1993

本文为博客迁移过来,原文链接: 实现简易EventBus:2021-7-11

最近在看一个文章,里面写到event,然后就想试一下,于是就写了一个简单的事件模块。

正好最近的工作一直都在就项目上写代码,很久没有接触ts,干脆以 Events 为例,用ts编写,jest单测,rollup打包编译。

初始化项目与安装rollup与rollup插件

npm init -y
npm i rollup rollup/plugin-typescript -D

创建rollup配置

// rollup.config.js
import typescript from '@rollup/plugin-typescript'

export default {
  input: 'src/index.ts',
  output: {
    dir: 'dist',
    format: 'cjs'
  },
  plugins: [typescript()]
}

新建 tsconfig.json 用于ts配置

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "./dist"
  },
	"include": ["src"]
}

单元测试

现在最流行的应该就是jest,而且各方面支持也不错,event只是一个简单的小库,不涉及ui界面还好一些。

有ts的话用 ts-jest初始化,或者也可以直接用 jest --init

npm install --save-dev jest typescript ts-jest @types/jest

npx ts-jest config:init 
或
npx jest --init

最后得到一份 jest.config.js

module.exports = {
	collectCoverage: true,
	coverageDirectory: "coverage",
	coverageProvider: "v8",
	preset: 'ts-jest',
	testEnvironment: "node",
}

编写单元测试

describe('添加监听函数', () => {
	test('on函数', () => {
		const ee = new EventEmiter()
		const fn = jest.fn()
		ee.on('test', () => {
			fn()
		})
		ee.emit('test')
		expect(fn.mock.calls.length).toBe(1)
	})
})

coding...

TDD特别适合这种翻译的项目,已经知道API和函数入参、出参等,写好各种测试用例,然后边写边跑测试用例...

比如看到Event.emit绑定的上下文是this

那可以先在测试文件里面写上测试用例,后面再根据这个测试用例去写代码,跑通了意味着代码功能实现。

// index.test.ts
test('this 指向', (done) => {
    const ee = new EventEmitter()
    ee.on('test', function() {
      expect(this).toEqual(ee)
      done()
    })
    ee.emit('test')
  })

修改package.json

{
	"main": "./dist/index.js",
	"types": "./dist/index.d.ts",
	"scripts": {
    "build": "npm test && rollup --config ./rollup.config.js",
    "watch": "rollup --config ./rollup.config.js --watch",
    "test": "jest"
  },
}

如果有需要发布到npm的,可以加一个 github action去发布。具体可以看 https://jsonz1993.github.io/npm-with-github-action/

仓库地址: https://github.com/jsonz1993/Events

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions