代码之家  ›  专栏  ›  技术社区  ›  Blankman

如何编写返回async的API调用的简单模拟

  •  0
  • Blankman  · 技术社区  · 7 年前

    这个示例应用程序有一个级别db Node JS库,但是我的服务器当前没有安装级别db,我不需要它。

    store变量是我要模拟的库,它有两个API调用:

      store.put   
      store.get
    

    const store = level('./data/dbname123', { valueEncoding: 'json' });
    
    save() {
      debug(`saving id: ${this.id}`);
      const properties = attributes.reduce((props, attr) => {
        props[attr] = this[attr];
        return props;
      }, { fields: this.fields });
      return new Promise((resolve, reject) => {
        store.put(this.id, properties, (error) => {
          if (error) { return reject(error); }
          resolve(this);
        });
      });
    }
    
    
     static find(id) {
        debug(`fetching id: ${id}`)
        return new Promise((resolve, reject) => {
          store.get(id, (error, properties) => {
            if (error) { return reject(error); }
            resolve(new Ticket(properties));
          });
        });
      }
    

    我怎么能很快嘲笑他们呢?我不太熟悉这种JavaScript风格,但因为promise包装器,我不确定这是异步调用还是?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Mark    7 年前

    你可以创建一个对象 put get

    显然,这可能会涉及更多,而且有一些工具 Sinon 如果必须模拟现有函数,这会有所帮助。

    例如:

    // simple mocks for store.get and store.put
    let store = {
        put(id, properties, fn){
            // add whatever behavior you need and call callback fn
            fn(null) // calling with null indicates no error. 
        },
        get(id, fn){
            // make some properties
            let props = {
                someProperties: "Hello",
                id: id
            }
            // call callback
            fn(null, props)
        }
    }
    
    
    function save() {
        return new Promise((resolve, reject) => {
          store.put('id', 'properties', (error) => {
            if (error) { return reject(error); }
            resolve();
          });
        });
      }
      
    function find(id) {
          return new Promise((resolve, reject) => {
            store.get(id, (error, properties) => {
              if (error) { return reject(error); }
              resolve(properties);
            });
          });
        }
    
    // try them out
    
    find("21")
    .then(console.log)
    
    save()
    .then(() => console.log("done"))
        2
  •  1
  •   Silvinus    7 年前

    也许我的答案与你的问题不符,但为了模仿你的库,你可以创建自己的存储

    const store = function () {
      var data = {};
    
      return {
        put: function(id, props, fn) {
           data[id] = props;
           fn(null);
        },
        get: function(id, fn) {
          fn(null, data[id]);
        } 
      }
    }();