This chapter is in direct contrast to the previous. In chapter 38, Judah shows no sign that he fears God whereas in chapter 39 Joseph is determined to fear God, and he continues to do so no matter what happens to him.
To begin with, Joseph prospered in God's providence and rose in responsibility in the household of Potiphar. His ability was recognised and the hand of God was clearly with him. We can see here how Christians can serve God successfully in a pagan environment without compromising their faith.
Yet Joseph was tested in his commitment by the persistent immoral suggestions of his master's wife. When he refused to do what she wanted, she concocted a story that made things look very bad for Joseph. Nevertheless Joseph realised that purity was more important than prominence. He had determined to put God first, even if it cost him his position.
We have to recall that God is still in control of the situation, even although things get very difficult for Joseph. In order to fulfil his purpose, God was willing for Joseph to be demoted and punished, even although he was innocent. The Lord allowed this to happen because he had great plans for Joseph. Many a Christian has had to walk this difficult path in which one difficult test is followed by another.
Did Joseph wonder why all this was going on? No doubt he did. He could recall the dreams he had been given by God when in Canaan, but everything seemed to suggest that they would not be fulfilled. Nevertheless he maintained his determination to fear God. Whether he was in a rich man's house or in a prison, his heart was in the right place.