github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/render/responder_test.go (about)

     1  package render_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"testing"
     8  
     9  	"github.com/hellofresh/janus/pkg/render"
    10  	"github.com/hellofresh/janus/pkg/test"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestRespondAsJson(t *testing.T) {
    15  	w := httptest.NewRecorder()
    16  
    17  	recipe := test.Recipe{Name: "Test"}
    18  	render.JSON(w, http.StatusOK, recipe)
    19  
    20  	assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
    21  	assert.Equal(t, http.StatusOK, w.Code)
    22  }
    23  
    24  func TestRespondExpectedBody(t *testing.T) {
    25  	w := httptest.NewRecorder()
    26  
    27  	recipe := test.Recipe{Name: "Test"}
    28  	render.JSON(w, http.StatusOK, recipe)
    29  
    30  	expectedWriter := httptest.NewRecorder()
    31  	json.NewEncoder(expectedWriter).Encode(recipe)
    32  
    33  	assert.Equal(t, expectedWriter.Body, w.Body)
    34  }
    35  
    36  func TestWrongJson(t *testing.T) {
    37  	w := httptest.NewRecorder()
    38  
    39  	render.JSON(w, http.StatusOK, make(chan int))
    40  
    41  	assert.Equal(t, http.StatusInternalServerError, w.Code)
    42  }