javascript - 单元测试链式承诺
问题描述
我将如何对调用作为承诺的导入类方法的类方法进行单元测试?我有以下结构:
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);
});
});
这仍然很简单,因为我不知道如何解决这个问题。分解then
s中的代码会更好吗?
更新
显然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
一个单独的函数并对其进行测试。
解决方案
您正在排除somePromiseMethod
存在的错误方法prototype
,SomeClass
因此您需要取而代之。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: [],
});
推荐阅读
- php - 我的路由组是否适用于需要正确编写管理员角色的路由?
- node.js - nodejs的链接文件地址的唯一GET()方法
- python - .py python 文件显示代码而不是在 webhost 上执行
- ansible - 在 playbook with_items 中运行所有任务
- azure-active-directory - 谷歌套件与 Azure Active Directory 的集成
- sass - sass:如何仅为移动设备渲染不同的图像
- email - 如何将 Outlook 发送的电子邮件与其相应的 Outlook 草稿(MAPI MailItem)唯一匹配
- c# - UWP XAML 和 C# - x:Bind 在 ResourceDictionary 内的 DataTemplate 上
- python - 使用 AWS SAM Local (Python) 访问 AWS 凭证
- makefile - 如何检查包含的 makefile 中的变量值?