Javascript 模拟来自同一类的承诺返回方法
我想模拟/存根一个类方法的解析,该类方法在测试同一类的另一个方法时返回一个承诺。我在用Javascript 模拟来自同一类的承诺返回方法,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我想模拟/存根一个类方法的解析,该类方法在测试同一类的另一个方法时返回一个承诺。我在用开玩笑 我有以下类Blah,我想测试其中的foo()方法: export default class Blah { foo () { this.bar().then(result => { // some logic here }) } bar () { return new Promise(function (resolve, reject) {
开玩笑
我有以下类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();让我们说,让它解决什么问题
假设测试看起来像这样:
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
谢谢,请原谅我的无知,为什么在这个上下文中使用\uuu
?@有趣的是,“我不在乎传递给这个函数的参数是什么”是一个相当常见的约定。下划线(和美元符号)是有效的JavaScript标识符。我本可以写blah.bar=dontcare=>Promise.resolve…
习惯的力量:)