Tesla Motors Inc. posted a surprise $22 million profit in its latest period, buoyed by record sales of its pricey electric cars and boosting Chief Executive Elon Musk’s plan to sharply lift output ahead of its release of a sedan to compete against mass-market rivals.

The Palo Alto, Calif., company reported its first profit after 12 quarterly losses amid a push to generate cash for building its $35,000 Model 3. The company has pledged to lift annual production to 500,000 cars in 2018, from about 50,000 last year.

The...