There are several ways to assess the traditions behind Genesis 40 and 41. They give us a clear break from chapter 39. At the end of 39 Joseph has become the supervisor of the prison. In 40, he seems to be a slave to two high-ranking prisoners (40:4). The story up to chapter 40 says that Joseph’s brothers had sold him into slavery. But in 40:15, Joseph claims to have been stolen out of the land of the Hebrews. Waiting on two high-ranking prisoners is not the same thing as being supervisor of the prison. And being sold into slavery doesn’t seem quite the same thing as being stolen out of one’s homeland.
So scholars have often seen at least two different stories coming together here. In Gerhard von Rad’s commentary on Genesis, for instance, we get a version of the documentary hypothesis. Most of chapter 39 comes from the Yahwist (J) source and most of 40 and 41 come from the Elohist (E) source. For him the emphasis on dreams in 40 and 41 is a mark of the Elohist source. We should note that in recent times the documentary hypothesis of sources J, E, P, and D has been hotly contested, and one of the reasons is that the E source’s existence, at least as a single document, is very hard to conceive. However, the documentary hypothesis has a lot of facts behind it. Most of them are gathered together in the article Torah by Richard Eliot Friedman in the Anchor Bible Dictionary.
A bit of a different perspective came from W. L. Humpheys in his article on the Story of Joseph in the supplementary volume to the Interpreter’s Bible Dictionary. He thought that 40-41 was once a separate courtier tale. This was an Egyptian genre that usually told of someone’s rise from low circumstances to become a high official in the land, a log cabin to the White House kind of story. He thought that Genesis 47:13-26, where Joseph saves Egypt from famine, was also part of the story. Also the notice about Joseph’s mummification in 50:26.
I find Humpheys’ idea intriguing. This part of the Joseph story never mentions the brothers. This part of the story also has most of the uniquely Egyptian elements of the story. It doesn’t necessarily contradict the notion that the story comes from a northern Israelite or E strand of the tradition. That tradition could already have incorporated the old Egyptian courtier’s tale.
So the story in these chapters really wasn’t part of the story of Joseph and his brothers, except that storytellers found it convenient to combine that story with the story of Joseph’s rise to power in Egypt. The thing to keep in mind is that Joseph’s situation at the end of chapter 39 does not quite match his situation at the beginning of chapter 40.