Treaties between countries are typically things that countries adhere to only for as long as it is convenient to them. This is true for many countries today and it was particularly true of Nazi Germany. Therefore, we should not be surprised that Nazi Germany broke the treaty and attacked.
When Germany signed the nonaggression pact with the Soviet Union, it was in their interest to do so. They wanted to prevent the Soviets from jumping in to the war when they invaded Poland. They signed the treaty about one week before they invaded Poland.
By June of 1941, the treaty was no longer useful to Germany, at least it was not in Hitler’s mind. Germany had conquered all of Western Europe but could not invade England. This meant that there was no longer any threat of war in the west. Because there was no such threat, it made sense to Hitler to attack to the east. He wanted to gain “lebensraum” for the German people by doing so. Therefore, he felt, he had something to gain from abrogating the treaty and nothing to lose (since he did not think his military could lose to the Soviets).