The race was the most expensive Senate contest in the nation. Mr. Toomey, 54, who once ran the free-market advocacy group Club for Growth, pitched himself to voters as a bipartisan deal maker, highlighting his effort to close loopholes in background checks for gun buyers after the 2012 massacre at Sandy Hook Elementary School in Connecticut.

Ms. McGinty, 53, a former aide to Gov. Tom Wolf and a onetime environmental adviser to President Bill Clinton, cast herself as a pro-business environmentalist and ran on a traditional Democratic platform, supporting abortion rights and an increased minimum wage.

With control of the Senate at stake, money poured in from outside groups, and spending topped $118 million, the Center for Responsive Politics reported.

Each side attacked the other on ethics; Republicans accused Ms. McGinty of using political ties to funnel business to a company where her husband worked as a consultant. Democrats accused Mr. Toomey of conflict of interest, holding stock in a bank of which he had been a founder while fighting new banking regulations.

But Ms. McGinty went into Election Day with a slight edge as the race tested whether Mr. Toomey could survive “the Trump drag,” said Jennifer Duffy, a non-partisan analyst for The Cook Political Report. The senator never endorsed Mr. Trump, and repeatedly ducked questions about whether he would vote for him.

On Tuesday, an hour before the polls closed, he revealed that he did.

—Sheryl Gay Stolberg

Wisconsin

MIDDLETON, Wis. — Senator Ron Johnson of Wisconsin, a Republican, on Tuesday fought off a challenge from former Senator Russ Feingold, retaining his seat in a Senate race critical to Republicans.

For more than a year this election cycle, Mr. Feingold appeared to be coasting to victory, with polls showing him holding a double-digit lead over Mr. Johnson, 61, a former manufacturing executive regarded as the most conservative of the blue state Republicans elected in recent years. They sparred over campaign finance, Mr. Feingold’s signature issue during his time in the Senate; the Affordable Care Act, which Mr. Feingold supported; and the economy in Wisconsin, where job growth has trailed its neighbors. Mr. Feingold said Mr. Johnson’s decisions had imperiled jobs in the state. Mr. Johnson called Mr. Feingold, 63, a “career politician,” and even some former Feingold supporters said they wondered if he were overstaying his welcome.