WASHINGTON — Republicans vowing to govern effectively as a congressional majority failed a fundamental test Friday, when House leaders only narrowly managed to avert a partial shutdown of the Department of Homeland Security after an embarrassing defeat earlier in the day.

The seven-day funding extension, approved by a vote of 357 to 60, came just hours before money for the department was to run out at midnight. The accord was reached after a stunning and humiliating setback for Speaker John A. Boehner and his leadership team earlier Friday, when the House voted against their original plan to extend funding for the department for three weeks — a position that Mr. Boehner had considered a fail-safe. More than 50 House Republicans defected, voting against the bill.

The speaker was rescued by Democrats, who supported his offer of a weeklong extension because they believed it would lead to a vote next week on full funding for the department through the fiscal year, without any provisions related to President Obama’s executive actions on immigration included in the House’s original legislation. A spokesman for Mr. Boehner said the speaker had made no promises or deals with House Democrats to guarantee such a vote.

“Your vote tonight will assure that we will vote for full funding next week,” wrote Representative Nancy Pelosi of California, the Democratic leader, in a letter to her members on Friday night urging them to support Mr. Boehner’s seven-day funding measure. The House vote came after the Senate had already agreed to a seven-day funding extension.