add testcase
This commit is contained in:
parent
95a538dbfe
commit
3173e66166
2
main.go
2
main.go
|
@ -27,6 +27,8 @@ func (e *EventEmitter) Once(event string, callback func(args ...interface{})) {
|
|||
defer e.lock.Unlock()
|
||||
|
||||
if _, ok := e.onceCallbacks[event]; !ok {
|
||||
e.onceCallbacks[event] = []func(args ...interface{}){callback}
|
||||
} else {
|
||||
e.onceCallbacks[event] = append(e.onceCallbacks[event], callback)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,60 @@
|
|||
package goemitter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEventEmitter_Emit(t *testing.T) {
|
||||
emitter := &EventEmitter{
|
||||
callbacks: make(map[string][]func(args ...interface{})),
|
||||
onceCallbacks: make(map[string][]func(args ...interface{})),
|
||||
}
|
||||
|
||||
// 注册一个普通回调函数
|
||||
emitter.callbacks["testEvent"] = append(emitter.callbacks["testEvent"], func(data ...interface{}) {
|
||||
t.Log("普通回调函数被调用")
|
||||
})
|
||||
|
||||
// 注册一个一次性回调函数
|
||||
emitter.onceCallbacks["testEvent"] = append(emitter.onceCallbacks["testEvent"], func(data ...interface{}) {
|
||||
t.Log("一次性回调函数被调用")
|
||||
})
|
||||
|
||||
// 触发事件
|
||||
emitter.Emit("testEvent", "testData")
|
||||
|
||||
// 等待一段时间,确保异步执行的回调函数完成
|
||||
time.Sleep(1 * time.Second)
|
||||
if len(emitter.onceCallbacks["testEvent"]) != 0 {
|
||||
t.Error("一次性回调函数没有被清除")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventEmitter_Once(t *testing.T) {
|
||||
emitter := &EventEmitter{
|
||||
onceCallbacks: make(map[string][]func(args ...interface{})),
|
||||
}
|
||||
|
||||
// 测试添加新事件和回调函数
|
||||
emitter.Once("event1", func(args ...interface{}) {})
|
||||
if len(emitter.onceCallbacks["event1"]) != 1 {
|
||||
t.Error("一次性回调函数添加失败")
|
||||
}
|
||||
|
||||
// 测试添加已存在事件的回调函数
|
||||
emitter.Once("event1", func(args ...interface{}) {})
|
||||
if len(emitter.onceCallbacks["event1"]) != 2 {
|
||||
t.Error("一次性回调函数再次添加失败")
|
||||
}
|
||||
|
||||
// 测试不存在的事件
|
||||
emitter.Once("event2", func(args ...interface{}) {})
|
||||
emitter.Emit("event1", "testData")
|
||||
|
||||
// 等待一段时间,确保异步执行的回调函数完成
|
||||
time.Sleep(1 * time.Second)
|
||||
if len(emitter.onceCallbacks["event1"]) != 0 {
|
||||
t.Error("一次性回调函数没有被清除")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue