我有一些中间件可以将带有请求 ID 的上下文添加到请求中。
func AddContextWithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ctx context.Context
ctx = NewContextWithRequestID(ctx, r)
next.ServeHTTP(w, r.WithContext(ctx))
})}
Run Code Online (Sandbox Code Playgroud)
我如何为此编写测试?
我想确保一个函数只被调用一次,这取决于一些道具和状态。
class MyComponent extends Component {
state = {
externalInfoPresent: false,
infoSaved: false,
}
async componentDidMount() {
await this.props.refreshExternalInfo();
this.setState({ externalInfoPresent: true });
if (this.props.externalInfo !== undefined && !this.state.infoSaved) {
await this.saveMyInfo();
}
}
async componentDidUpdate(prevProps) {
if (prevProps.externalInfo === this.props.externalInfo || this.state.infoSaved) return;
await this.saveMyInfo();
}
async saveMyInfo() {
if (this.props.externalInfo === undefined || this.state.infoSaved) return;
// logic for saving stuff to external service
this.setState({ infoSaved });
}
// render and other stuff
}
Run Code Online (Sandbox Code Playgroud)
saveMyInfo()取决于externalInfo在场。
我 …