1

我想对这段代码进行单元测试,该代码是使用 Clasp 将 Typescript 转换为 Google App Script 的:

function onLinksInText(text: GoogleAppsScript.Document.Text, onLink: OnLinkCallback) {
    const iterator = new TextIterator(text, onLink)
    const characters = text.getText();
    for (let i = 0; i < characters.length; i++) {
        iterator.handle(i, text.getLinkUrl(i));
    }
    iterator.end()
}

为此,我需要创建一个实例GoogleAppsScript.Document.Text

我怎么做?

4

1 回答 1

1

简短的回答

你将不得不嘲笑这个班级。

长答案

要成功测试该功能,您只需要构造函数getText和模拟的getLinkUrl方法。让我们也模拟一下setText

function TextFactory() {

  const linkMatcher = /https?:\/\/(?:www\.)?(?:\.{0,1}(?:\w|-)+)+/ig;

  let private = "";
  
  return {
    setText(text) {
      private = text.toString();
      return this;
    },
    getText() {
      return private;
    },
    getLinkUrl(offset) {
      const idx = private.search(linkMatcher);
            
      if(idx < 0 || offset > idx ) { return null; }
      
      return private.slice(idx);
    }
  };
}

const mock = TextFactory();
mock.setText("Find me at https://example.com ");

console.log(mock.getText());
console.log(mock.getLinkUrl(4));
console.log(mock.getLinkUrl(12));

我假设TextIterator是你的自定义类,所以,为了演示,我做了一个简单的浅模拟:

function TextFactory() {

  const linkMatcher = /https?:\/\/(?:www\.)?(?:\.{0,1}(?:\w|-)+)+/ig;

  let private = "";
  
  return {
    setText(text) {
      private = text.toString();
      return this;
    },
    getText() {
      return private;
    },
    getLinkUrl(offset) {
      const idx = private.search(linkMatcher);
            
      if(idx < 0 || offset > idx ) { return null; }
      
      return private.slice(idx);
    }
  };
}

const mock = TextFactory();
mock.setText("Find me at https://example.com ");

class TextIterator {

  constructor(text, onLink) {
    this.text = text;
    this.callback = onLink;
  }

  handle(index, link) {
    this.callback(`${link} at index ${index}`);
  }

  end() {
    console.log("ended");
  }
}


function onLinksInText(text, onLink) {
    const iterator = new TextIterator(text, onLink)
    const characters = text.getText();
    for (let i = 0; i < characters.length; i++) {
        iterator.handle(i, text.getLinkUrl(i));
    }
    iterator.end()
}

onLinksInText(mock, console.log );

参考

  1. Text课堂文档
于 2020-09-28T01:02:52.317 回答