小编scu*_*uit的帖子

测试修改请求的 golang 中间件

我有一些中间件可以将带有请求 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)

我如何为此编写测试?

testing middleware go

6
推荐指数
1
解决办法
5389
查看次数

确保函数只在 componentDidMount 或 componentDidUpdate 中调用一次

我想确保一个函数只被调用一次,这取决于一些道具和状态。

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在场。

我 …

javascript reactjs

3
推荐指数
1
解决办法
2373
查看次数

标签 统计

go ×1

javascript ×1

middleware ×1

reactjs ×1

testing ×1