繁体   English   中英

Jest 实例的 Mocking 方法

[英]Mocking method of instance with 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM