Shopify / shopify_app

A Rails Engine for building Shopify Apps
MIT License
1.73k stars 682 forks source link

Testing helpers not compatible with token exchange #1867

Open kirillplatonov opened 2 weeks ago

kirillplatonov commented 2 weeks ago

Issue summary

I'm using shopify_app v22.2.1 with enabled token exchange.

I was trying to write a test for an app that upgraded to token exchange. But old way to stub session no longer works: https://github.com/Shopify/shopify_app/blob/main/docs/shopify_app/testing.md

require "test_helper"
require 'shopify_app/test_helpers/shopify_session_helper'

class HomeControllerTest < ActionDispatch::IntegrationTest
  include ShopifyApp::TestHelpers::ShopifySessionHelper

  def setup
    @shop = shops(:regular)
    setup_shopify_session(session_id: "1", shop_domain: @shop.shopify_domain)
  end

  test "renders home page" do
    get home_path

    assert_response :success
  end
end

Expected behavior

setup_shopify_session should stub the session and skip ID token check.

Actual behavior

I'm getting error ShopifyAPI::Errors::MissingJwtTokenError:

# Running:

E

Error:
HomeControllerTest#test_renders_home_page:
ShopifyAPI::Errors::MissingJwtTokenError: Missing Shopify ID Token
    test/controllers/home_controller_test.rb:14:in `block in <class:HomeControllerTest>'

bin/rails test test/controllers/home_controller_test.rb:13

Finished in 0.104336s, 9.5844 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

Steps to reproduce the problem

  1. Create an app with new token exchange auth
  2. Try to write a test using setup_shopify_session helper
kirillplatonov commented 2 weeks ago

@zzooeeyy it seems like test helpers and testing documentation require an update

zzooeeyy commented 2 weeks ago

Good call out! I'll add that to our backlog

kirillplatonov commented 2 weeks ago

I was able to fix it with a simple patch to helper:

def setup_shopify_session(session_id:, shop_domain:)
  ShopifyAPI::Auth::Session.new(id: session_id, shop: shop_domain).tap do |session|
    ShopifyApp::SessionRepository.stubs(:load_session).returns(session)
    ShopifyAPI::Utils::SessionUtils.stubs(:current_session_id).returns(session.id)
+   ShopifyAPI::Utils::SessionUtils.stubs(:session_id_from_shopify_id_token).returns(session.id)
    ShopifyAPI::Context.activate_session(session)
  end
end