模拟从另一个函数返回的简单闭函数



我有一个名为fnCreater的函数,它创建了另一个函数:

const fnCreater = (page, extraCondition = false) => () => {
if (extraCondition) return;
ViewStore.setCurrentPage = page;
}

我希望能够测试返回的函数是否被调用:

describe('test', () => {
it('should return a function', () => {
const fn = fnCreater('CONFIGURATOR')
expect(typeof fn).toBe('function')
})
it('should be able to execute the function from the closure', () => {
const fn = fnCreater('CONFIGURATOR')
// const spy = jest.spyOn(fn) // needs a 'module'
fn();
expect(fn).toHaveBeenCalled()
})
})

我不太熟悉jest,但是测试返回这个错误:

Matcher error: received value must be a mock or spy function
Received has type:  function
Received has value: [Function anonymous]

我不明白如何解决这个问题,或者为什么错误是声明需要一个spy或mock - spyOn需要一个对象,mock需要一个模块。fnCreater函数本身返回另一个函数(fn),我想确定关闭函数是否已被调用。如何做到这一点?

您是否试图测试fncreator或调用它的代码?

如果你正在测试fnCreater本身,你不应该模拟它。

我建议调用fnCreater,然后调用返回的Function并断言正确的页面被设置。

最新更新