如何在JavaScript中从库中模拟函数

时间:2019-08-26 08:26:43

标签: javascript unit-testing jestjs sinon

我有一些代码导入了easysoap库,以从WSDL获取请求。而且我正在尝试重构我的单元测试。

我用玩笑编写了单元测试,并模拟了返回值,但这被称为真正的端点

我的函数requestConverter.helper.ts

import * as EasySoap from 'easysoap';
export async function requestConverter(params, method, body) {
  const opts = {
    secure: false
  };
  const easySoap = await EasySoap(params, opts);
  try {
    const result = easySoap.call({
      method,
      params: body
    });
    return result[`data`];
  } catch (err) {
    return err;
  }
}

我的测试文件

import { requestConverter } from '../helpers/requestConverter.helper';
import * as EasySoap from 'easysoap';

describe('covert http request to wsdl request', () => {
  let params: object;
  let method: string;
  let body: object;
  let expectedResponse: object;
  let opts: object;
  beforeEach(() => {
    params = {
      host: '223.27.147.38',
      path: '/~kabgianyar/ppobwebservice/develop/webservice-pdam/CustomerBillingPelInfo3Tagihan.php',
      wsdl: '/~kabgianyar/ppobwebservice/develop/webservice-pdam/CustomerBillingPelInfo3Tagihan.php?wsdl'
    };
    method = 'billinfo';
    body = {
      namapengguna: 'value',
      katasandi: 'abs'
    };
    expectedResponse = {
      billinfoResponse: {
        'xmlns:ns1': 'http://schemas.xmlsoap.org/soap/envelope/',
        "return": 'mocked'
      }
    };
    opts = {
      secure: false
    };
  });
  afterEach(() => jest.restoreAllMocks());
  it('should return response from wsdl', async () => {
    jest.spyOn(EasySoap, 'call').mockImplementation(jest.fn().mockReturnValue(expectedResponse));
    const result = await requestConverter(params, method, body);
    expect(EasySoap.call).toBeCalled();
    console.log(JSON.stringify(result), '====');
  });
});

我希望回复是

expectedResponse = {
  billinfoResponse: {
    'xmlns:ns1': 'http://schemas.xmlsoap.org/soap/envelope/',
    "return": 'mocked'
  }
};

0 个答案:

没有答案