javascript - 用 Jest 模拟实例的方法
问题描述
如何模拟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({})
})
})
解决方案
您可以使用jest.mock
模拟jayson/promise
模块。不需要使用jest.spyOn
.
例如
index.ts
:
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 });
}
index.test.ts
:</p>
import { dispatch } from './';
import jayson, { HttpsClient } from 'jayson/promise';
import { mocked } from 'ts-jest';
jest.mock('jayson/promise');
const httpsClientMock = mocked(jayson.Client.https);
describe('65924278', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', async () => {
const url = 'http://example.com:8000';
const method = '';
const payload = {};
const serviceMock = ({
request: jest.fn(),
} as unknown) as HttpsClient;
httpsClientMock.mockReturnValueOnce(serviceMock);
await dispatch(url, method, payload);
expect(jayson.Client.https).toBeCalledTimes(1);
expect(serviceMock.request).toBeCalledWith('', {});
});
});
单元测试结果:
PASS examples/65924278/index.test.ts (10.748 s)
65924278
√ should pass (13 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.15 s
推荐阅读
- node.js - 从路由控制器 _ express + nodejs + webSocket 向 Web 套接字发布消息
- javascript - setState 之后事件侦听器处理程序中的状态值错误
- json - Splunk 查询从 json 日志事件中检索值并将其获取到表中
- r - 如何使用R获得同一数据框列中的值之间的配对差异
- javascript - 在 Typescript/Javascript ES6 中以编程方式在同一文件中获取模块的所有导出
- react-native - 博览会通知不适用于独立 APK 应用 SDK 38
- process - Camunda 迁移已完成的流程实例
- python - 如何解决No module named ROOT的问题?
- hibernate - Hibernate 搜索:在复合键 EmbeddedId 中搜索
- xamarin - Xamarin 在状态码为 500 时获取 API 结果