我无法在jest中模拟静态方法.想象一下,你有一个静态方法的A类:
export default class A {
f() {
return 'a.f()'
}
static staticF () {
return 'A.staticF()'
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个进口A的B级
import A from './a'
export default class B {
g() {
const a = new A()
return a.f()
}
gCallsStaticF() {
return A.staticF()
}
}
Run Code Online (Sandbox Code Playgroud)
现在你要模拟A.很容易模拟f():
import A from '../src/a'
import B from '../src/b'
jest.mock('../src/a', () => {
return jest.fn().mockImplementation(() => {
return { f: () => { return 'mockedA.f()'} }
})
})
describe('Wallet', () => {
it('should work', () …Run Code Online (Sandbox Code Playgroud) 考虑一种情况,你有一个B类从A类扩展.你创建一个B类型的对象,并调用A中定义的方法fooA,然后调用B中定义的方法fooB.
class A {
fooA () {
console.log('fooA called')
return this
}
}
class B extends A {
fooB () {
console.log('fooB called')
return this
}
}
new B().fooA().fooB()
Run Code Online (Sandbox Code Playgroud)
运行时,代码按预期记录以下内容
fooA called
fooB called
Run Code Online (Sandbox Code Playgroud)
所以Javascript理解这new B().fooA()是B类的对象.但是Flow给出了以下错误消息:
Cannot call new B().fooA().fooB because property fooB is missing in A
Run Code Online (Sandbox Code Playgroud)
该怎么办?我对一个解决方案感兴趣,我不需要更改父类A,因为它是在npm包中定义的.我可以改变B.