1

I am making a Rails app with some of my views rendered in React, using the react-rails gem (so it's using the asset pipeline).

When I try to test my React views, the React components are not loaded, so I cannot test their content. For example, one of my integration tests look like this:

require 'test_helper'

class TabsIndexTest < ActionDispatch::IntegrationTest

  test "index" do
    get tabs_path
    assert_template 'tabs/index'
    assert_select 'table'
  end
end

This tests if this index page has a table element. It should, but the test is not loading my React element so it does not see one. (However, if I test for the presence of <div data-react-class=...>, that passes, letting me know the JS has not run).

Is there any way to get my React components to be visible to my Minitest tests?

1

2 Answers 2

1

I'd recommend not testing the components like this in a functional test.

many of the assert_'s are heading out of style in Rails. Really a controller test should only check for HTTP status codes (:ok, :not_found)

More info here: https://github.com/rails/rails/issues/18950

If you really want to test component in this way, you are able to use integration tests with capybara and something like headless chrome to execute the JS

Quick write up here: https://robots.thoughtbot.com/headless-feature-specs-with-chrome

I personally would recommend instead using JS unit tests and/or snapshots, which in my experience are quick and friendly:

https://facebook.github.io/jest/docs/en/tutorial-react.html https://facebook.github.io/jest/docs/en/snapshot-testing.html

Sign up to request clarification or add additional context in comments.

Comments

0

a very simple solution (instead of using jasmine etc.) was making those helpers:

  def assert_async_js_equal(expected, script)
    script = <<~SCRIPT
      done = arguments[arguments.length - 1];
      #{script}.then((result) => {
        done(result)
      })
    SCRIPT

    assert_equal(expected, page.evaluate_async_script(script), script)
  end

  def assert_js_equal(expected, script)
    assert_equal(expected, evaluate_script(script), script)
  end

then you can do:

assert_async_js_equal("your_value", "your.promise('code')")
assert_js_equal([1, 2, 3], "[1, 1 + 1, 2 + 1]")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.