4

这就是我的一个拦截函数现在的样子:

interceptWithError() {
  nock(baseUrl)
    .get(/.*/)
    .replyWithError(500);

  nock(baseUrl)
    .put(/.*/)
    .replyWithError(500);

  nock(baseUrl)
    .post(/.*/)
    .replyWithError(500);

  nock(baseUrl)
    .delete(/.*/)
    .replyWithError(500);
}

我想避免重复,并通过执行以下操作为其提供更大的灵活性:

interceptWithError(params) {
  const verb = params && params.verb;
  const stat = params && params.stat;

  return nock(baseUrl)
    .[verb]    // something like this!!!
    .replyWithError(stat)
}

有没有办法这样做???

4

1 回答 1

0

这就是我想出的:)

baseNock(url) {
  return this.nock(url)
    .replyContentLength()
    .defaultReplyHeaders({ 'Content-Type': 'application/json' });
}

interceptWithError(verbCodeMap) {
  const verbs = (verbCodeMap && Object.keys(verbCodeMap))
    || ['post', 'get', 'put', 'delete'];

  return verbs.map(verb => 
    baseNock(someUrl)[verb](/.*/)
      .replyWithError((verbCodeMap && verbCodeMap[verb]) || 500));    
}
于 2017-07-31T16:27:13.943 回答