WICHITA, Kan. — Ron Estes, the Republican candidate for an empty House seat in Kansas, survived a surprisingly competitive race in a heavily conservative district on Tuesday. He defeated James Thompson, the Democratic candidate, in the first national test of the Republican Party’s electoral strength, in a contest that saw a late infusion of national support from Republicans nervous about the tumultuous political environment during President Trump’s initial months in office.

Mr. Estes, 60, the state treasurer, overcame the challenge by Mr. Thompson, a Wichita civil rights lawyer, and won by a count of 53 percent of the vote to 46 percent, according to unofficial results, to fill the seat in the district that was vacated by Mike Pompeo, now the C.I.A. director. In a race more than a year before the midterm elections, Mr. Estes was initially expected to cruise to victory in a district that his party has held for more than two decades and that Mr. Trump won by 27 points.

But after internal Republican polling last week revealed Mr. Estes’s lead was in only the single digits, the national party scrambled to rescue his campaign — and effectively conceded that even seats in the reddest corners of the United States are not safe at a time when Democrats are so energized against Mr. Trump.

In his victory speech late Tuesday, Mr. Estes took aim at those who thought he might lose.

“The pundits were talking about — this wasn’t a seat we were going to win,” Mr. Estes said before several hundred people in a hotel ballroom, “that we were going to lose a Republican seat, that it was a special election, that it was a chance for the Democrats, they were motivated, there was a lot of angst against the president. But we really showed the pundits tonight, didn’t we?”