我想模拟/ stub 一个类方法的解析,该类方法在测试同一类的另一个方法时返回一个 promise 。我正在使用jest
。
我有以下类 Blah
,我想测试其中的 foo()
方法:
export default class Blah {
foo () {
this.bar().then(result => {
// some logic here
})
}
bar () {
return new Promise(function (resolve, reject) {
// fetches some stuff over the network
resolve('hello world')
})
}
}
因为 foo()
使用 bar()
- 一个通过网络执行操作的 promise 返回方法 - 我想模拟 bar( );
;假设让它解决发生了什么
。
假设测试如下所示:
import Blah from './blah'
test('foo() - bar() resolves "what up"', () => {
const blah = new Blah()
// mock blah.bar() so that is resolves "what up"
// {some assertions on blah.foo() here}
})
这是我第一次使用 jest
,并且我已经通读了文档,但我仍然很难理解这个案例。
如何在测试 foo()
时模拟 bar()
的解析值?
最佳答案
仍然只是 JavaScript 意味着任何对象属性都可以动态覆盖:
// in the test file
const blah = new Blah();
blah.bar = _ => Promise.resolve("what up");
// now some assertions about blah.foo
关于javascript - 模拟来自同一个类的 promise 返回方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610380/