首页 > 解决方案 > 单元测试链式承诺

问题描述

我将如何对调用作为承诺的导入类方法的类方法进行单元测试?我有以下结构:

import { SomeClass } from 'some-library';

class MyClass extends AnotherClass {
  myMethod() {
    const someClass = new SomeClass();

    return someClass.somePromiseMethod('someParam')
      .then(response => response.data)
      .then(response => {
        // Do stuff
      });
  }
}

我有以下测试

describe('myMethod', () => {
  it('does something', async () => {
    const inst = new MyClass();
    const stub = sinon.stub(SomeClass, 'somePromiseMethod')
      .resolves(Promise.resolve({
        data: [],
      }));

    await inst.myMethod();

    expect(stub.callCount).to.equal(1);
  });
});

这仍然很简单,因为我不知道如何解决这个问题。分解thens中的代码会更好吗?

更新

显然SomeClass是一个单例,而 sinon 抛出了一个错误,说somePromiseMethod是一个non-existent own property. 我将存根更改为调用它prototype,现在正在调用存根。

class MyClass extends AnotherClass {
  myMethod() {
    const someClassInstance = SomeClass.getInstance();

    return someClassInstance.somePromiseMethod('someParam')
      .then(response => response.data)
      .then(response => {
        // Do stuff
      });
  }
}


describe('myMethod', () => {
  it('does something', async () => {
    const inst = new MyClass();
    const stub = sinon.stub(SomeClass.prototype, 'somePromiseMethod')
      .resolves(Promise.resolve({
        data: [],
      }));

    await inst.myMethod();

    expect(stub.callCount).to.equal(1);
  });
});

现在,从那时起 secondthen只会返回data,我可以放入//Do stuff一个单独的函数并对其进行测试。

标签: javascriptunit-testingpromisesinon

解决方案


您正在排除somePromiseMethod存在的错误方法prototypeSomeClass因此您需要取而代之。Sinon 应该让您执行以下操作:

const stub = sinon.stub(SomeClass.prototype, 'somePromiseMethod')
  // You may be able to remove the Promise.resolve as well, as I think resolves does this for you
  .resolves({
    data: [],
  });

推荐阅读