A group for which the power map $f(x) = x^n$ is a homomorphism is called an “$n$-abelian group.” Such a group satisfies the identity $(xy)^n = x^ny^n$ for all $n$.
The structure of $n$-abelian groups was determined by Alperin:
Theorem. (Alperin) A group $G$ is $n$-abelian if and only if there exist groups $A$, $M$, and $N$, and $S$ such that:
- $A$ is abelian;
- $M$ is of exponent $n$;
- $N$ is of exponent $n-1$;
- $S$ is a subgroup of $A\times M\times N$; and
- $G$ is isomorphic to a quotient of $S$.
If you want your group to be nonabelian, the smallest exponent you can get is $6$ (with $S_3$), so you get the example given by @DonAntonio. Note that the map $f\colon S_3\to S_3$ given by $f(x)=x^7$ is also a homomorphism (in this case an automorphism) of $S_3$.
The next smallest example is with groups of order $8$; the dihedral group $D_8$ and the quaternion group $D_8$ are both of exponent $4$, so the maps $f(x)=x^4$ and $f(x)=x^5$ are homomorphisms for both.
The smallest example with smallest possible $n$ is for $n=3$ (since a $2$-abelian group is abelian); this is the nonabelian group of order $3^3$ and exponent $3$, sometimes called the Heisenberg group for $p=3$.
Remark. The apparent complication of Alperin’s description is related to the fact that groups that satisfy the identity $(xy)^n=x^ny^n$ form a variety. By a theorem of Birkhoff, a collection of groups is a variety if and only if it is closed under the construction of subgroups, arbitrary direct products, and homomorphic images, and the smallest variety that contains a collection $\mathscr{X}$ of group is exactly the collection of all homomorphic images of subgroups of direct products of groups in $\mathscr{X}$; this is often called Birhoff’s $\mathbf{HSP}$ Theorem, since it states that $\mathrm{Var}(\mathscr{X})=\mathbf{HSP}(\mathscr{X})$. So Alperin is saying that the variety of $n$-abelian groups is precisely the join of the varieties of abelian groups, groups of exponent $n$, and groups of exponent $n-1$, all of which clearly are $n$-abelian.
References.
Alperin, J.L. A classification of $n$-abelian groups. Canadian J. Mathematics, 21 (1969), pp. 1238-1244.
Bergman, G.M. An Invitation to General Algebra and Universal Constructions. 2nd Edition. Springer-Verlag Universitext, 2015. Birhoff’s Theorem appears as Theorem 9.6.1 on p. 416.