Displacement or Coping
In Freudian psychology, displacement is an unconscious defense mechanism whereby the mind substitutes … a new object for goals felt in their original form to be dangerous or unacceptable.
A term originating with Sigmund Freud, displacement operates in the mind unconsciously, its transference of emotions, ideas, or wishes being most often used to allay anxiety in the face of aggressive … impulses.
Source: Displacement (psychology) - Wikipedia, the free encyclopedia
Displacement is not about the type of humor used, rather about why it is used, but I think it accurately describes the scenario you present. Furthermore…
Freud also saw displacement as occurring in jokes…
According to Gina Barreca Ph.D. in an article for Psychology Today:
We can use humor to put our fears into perspective. Humor addresses the same issues as fear, not to dismiss them, but to strengthen our ability to confront them and then laugh them away from the door.
Humor is, of course, the one thing that fear cannot abide: Laughter banishes anxiety, and can help replace fear. Laughter is a testament to courage, or at least a manifestation of the wish for it, and courage is stronger than fear.
However, she seems to be describing humor here as a conscious alternative to the typical unconscious displacement of "our feelings of fear onto other, perhaps even more potentially destructive, emotions and behaviors."
You might use the word coping or phrase coping mechanism to describe the conscious use of humor in this scenario.
So whether unconscious or conscious, it could be described as a type of "displacement" or "coping" humor.
Additionally, you could use the word macabre to qualify it: "We joked about the terminal diagnosis as a sort of macabre coping mechanism."