简体   繁体   English

单元测试链式承诺

[英]Unit testing chained promises

How would I unit test a class method that calls an imported class's method that is a promise? 如何对一个调用已承诺的导入类方法的类方法进行单元测试? I have the following structure: 我有以下结构:

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
      });
  }
}

I have the following test 我有以下测试

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);
  });
});

Which is still pretty bare as I'm not sure how to approach this. 由于我不确定该如何处理,所以这还很裸露。 Would it be better to break down the code in the then s? then s中分解代码会更好吗?

UPDATE UPDATE

Apparently SomeClass is a singleton and sinon was throwing an error saying somePromiseMethod is a non-existent own property . 显然SomeClass是一个单例,并且sinon抛出错误,指出somePromiseMethodnon-existent own property I changed the stub to call on its prototype instead and now the stub is being called. 我将存根更改为调用其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);
  });
});

Now, since then second then would just return data , I could just put //Do stuff in a separate function and test that. 现在,从第二秒then就只返回data ,我可以将//Do stuff放到一个单独的函数中并进行测试。

You are stubbing out the wrong method somePromiseMethod exists on the prototype of SomeClass so you need to stub that instead. 您正在存出错误的方法SomeClassprototype上存在somePromiseMethod ,因此您需要存根。 Sinon should let you do something like: 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: [],
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM