【发布时间】:2021-01-27 17:28:24
【问题描述】:
如何在下面的代码中模拟service.request的调用?
import url from 'url'
import jayson from 'jayson/promise'
export async function dispatch(webHook, method, payload) {
const service = jayson.Client.https({ ...url.parse(webHook) })
return service.request(method, { ...payload })
}
在我的单元测试中,我想做这样的事情
jest.mock("") // what should go here?
it(() => {
const method = 'test'
expect(request).toHaveBeenCalledWith(method...) ?
})
更新
我用我的发现更新了我的代码,但仍然没有运气
import { Client } from 'jayson/promise'
import { dispatch } from '../src/remote'
jest.mock('jayson')
describe('remote', () => {
let spy: jest.SpyInstance<any>
beforeEach(() => {
spy = jest.spyOn(Client.https.prototype, 'request')
})
afterEach(() => {
spy.mockClear()
})
it('should invoke request method', () => {
const url = 'http://example.com:8000'
const method = ''
const payload = {}
dispatch(url, method, payload)
expect(spy).toHaveBeenCalledWith({})
})
})
【问题讨论】:
标签: javascript unit-testing jestjs mocking