Iteration on #5237 to add unit tests

This pull request iterates on #5237 to add unit tests to terms and histogram aggregations when sorting on sub-aggregations that return NaN (eg. an average aggregation over an empty set).