The normal optional argument provided by LaTeX uses \futurelet (i.e. over \@ifnextchar) to look ahead if the next token is [. This is an assignment which is not expandable, but has to be executed.
The etextools package provides \FE@testopt as a fully expandable (FE) version of the core LaTeX macro \@testopt with is IIRC used by macros with optional arguments defined by \newcommand.
This however has the limitation that the macro must have at least one mandatory argument and is not called with {[}.
The general usage is:
\def\MacroWithOption#1{\FE@testopt{#1}{\MacroHasOption}{default value}}
See section 6 Fully expandable macros with options and modifiers of the package manual for all details. It uses eTeX's \detokenize to test #1 safely.
Your example could be written like this using the package:
\documentclass{article}
\usepackage{etextools}
\makeatletter
\newcommand{\test}[2]{got #1 and #2}
\def\testopt#1{\FE@testopt{#1}{\test@opt}{nothing}}
\def\test@opt[#1]#2{got #1 and #2}
\makeatother
\begin{document}
\ttfamily
\edef\result{\test{one}{two}}
\meaning\result
\edef\result{\testopt{two}}
\meaning\result
\end{document}
This gives:
macro:->got one and two
macro:->got nothing and two
I myself implemented a similar fully expandable optional argument test macro for my newer filemod package. However, it is only intended to accept simple optional arguments (a single number) and might break with more complex input.
pgfmathresult). See also macros - Is it possible to define a command taking an optional star and working in a subscript? - TeX - LaTeX Stack Exchange for some other "workaround" for unexpandable optional argument/star. – user202729 Jan 07 '22 at 00:52