How can I load a JavaScript file only when a page has an element whose class is "test"?
Well one way would be to just add the script always and check for the existence of test class there.
(function ($, Drupal) {
    Drupal.behaviors.tester = {

        attach: function (context) {
           if (context.querySelector('.test')) {
               // Do something
               // Or maybe load another JS file dynamically
           }   
        }

})(jQuery, Drupal);