Add method to assert an event has been dispatched

This commit is contained in:
kolaente 2021-02-02 19:46:45 +01:00
parent 3280aace9d
commit 217a09f723
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
3 changed files with 26 additions and 1 deletions

View File

@ -80,6 +80,7 @@ func InitEvents() (err error) {
func Publish(event Event) error {
if isUnderTest {
dispatchedTestEvents = append(dispatchedTestEvents, event)
return nil
}

View File

@ -16,11 +16,33 @@
package events
var isUnderTest bool
import (
"github.com/stretchr/testify/assert"
"testing"
)
var (
isUnderTest bool
dispatchedTestEvents []Event
)
// Fake sets up the "test mode" of the events package. Typically you'd call this function in the TestMain function
// in the package you're testing. It will prevent any events from being fired, instead they will be recorded and be
// available for assertions.
func Fake() {
isUnderTest = true
dispatchedTestEvents = nil
}
// AssertDispatched asserts an event has been dispatched.
func AssertDispatched(t *testing.T, event Event) {
var found bool
for _, testEvent := range dispatchedTestEvents {
if event.TopicName() == testEvent.TopicName() {
found = true
break
}
}
assert.True(t, found, "Failed to assert "+event.TopicName()+" has been dispatched.")
}

View File

@ -17,6 +17,7 @@
package models
import (
"code.vikunja.io/api/pkg/events"
"testing"
"time"
@ -65,6 +66,7 @@ func TestTask_Create(t *testing.T) {
"bucket_id": 1,
}, false)
events.AssertDispatched(t, &TaskCreatedEvent{})
})
t.Run("empty title", func(t *testing.T) {
db.LoadAndAssertFixtures(t)