最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

带有存根的函数返回promise

运维笔记admin8浏览0评论

带有存根的函数返回promise

带有存根的函数返回promise

我不熟悉在摩卡咖啡中编写单元测试。我有一个名为appStore的函数:

public appStore(name) {
    return this.connector.findOne(name).then((record) => {
      if (!record) {
        throw new Error("Record not found");
      }
      return record.data;
    });
  }

这里record.data是包含以下内容的对象:

{ 
    a: "ValueA", 
    b: "ValueB", 
    c: "ValueC" 
}

我试图对函数进行存根。但无法正确获取它。

import myClass from "testClass.service";
describe("MyModule", () => {
  const sandbox = sinon.createSandbox();
  let valTest;
  beforeEach(() => {
    const userObj = { 
        a: "ValueA", 
        b: "ValueB", 
        c: "ValueC" 
    };
    valTest = sandbox.stub(myClass , "appStore").returns(userObj );
  });
  afterEach(() => {
    sandbox.restore();
  });
  it("myfunc1 is a proxy for myfunc2", () => {

     expect(myClass.appStore("dataname")).to.eql(userObj );
  });
});

如果我做错了,请纠正我,因为我是初学者。任何帮助将不胜感激。

预先感谢。

回答如下:

通常,您不想在类上添加方法,而只在该类的单个对象上添加方法。

import myClass from "testClass.service";
describe("MyModule", () => {
  const sandbox = sinon.createSandbox();
  const myInstance = new myClass();
  let valTest;
  beforeEach(() => {
    const userObj = { 
        a: "ValueA", 
        b: "ValueB", 
        c: "ValueC" 
    };
    valTest = sandbox.stub(myInstance , "appStore").resolves(userObj );
  });
  afterEach(() => {
    sandbox.restore();
  });
  it("myfunc1 is a proxy for myfunc2", () => {

     expect(myInstance.appStore("dataname")).to.eql(userObj );
  });
});

如果您真的想对从特定类派生的所有对象都使用非静态方法,则可以在原型上进行。

sandbox.stub(myClass.prototype, "appStore").resolves(userObj);

appStore方法在类本身上仍然不存在,但是您可以使用任何对象来验证存根是否可以工作。

expect((new myClass).appStore("dataname")).to.eql(userObj);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论