Unit testing & cookies

I’m not really sure how to even describe this :slight_smile:
I am making use of cookies as a store. I’d like to test the controller code that uses the cookies. Now, I don’t want to actually create and delete the cookies in the browser. I’d like to just have the data in the conn.
Creating the tests I can use setup to customise :cookie in conn. But my endpoint call is a post request. I think this resets the conn with my custom cookie info. Once the controller is reached the :cookie in conn is empty. However, the customised cookie info is gone with a simple get request too.
How can I mock a browser cookie data in my tests?

When I post I often arrive at a solution in short order :wink:

This post was helpful solve my problem:
https://stackoverflow.com/questions/31983077/how-can-i-set-session-in-setup-when-i-test-phoenix-action-which-need-user-id-in

Here’s my code:

  setup do
    conn =
      build_conn(:get, "/")
      |> Map.put(:secret_key_base, String.duplicate("abcdefgh", 8))
      |> Plug.Session.call(@session)
      |> Plug.Conn.fetch_session()
      |> Map.replace!(:cookies, @cookies)
    {:ok, conn: conn}
  end

The @session module attribute is as shown in the stackoverflow link. @cookies is just a simple map of the cookie data as it is read from the browser store.

This works with a get request - now to try with a post :slight_smile: Edit: it did!

4 Likes