类型从不的“ Jest”接口属性-模拟和测试消息

时间:2020-08-05 18:28:46

标签: typescript jestjs babel-jest ts-jest jest-fetch-mock

我们有一个来自nodemodules的接口

declare namespace CbServer {     
    interface Resp {
        error(msg: any): never;
        success(msg: any): never;
    }
}

在dh.js中

 const getDataFromRequest = (req, resp) => {
 
 if (req) {
    var data = {
      dName: req.params.body.d_id,
      requestData: req.params.body,
      dColName: `SD-${req.params.body.d_id}`
    }
    return data;
  }
  return resp.error('failed');
}
module.exports = getDataFromRequest;

使用Jest为上述方法编写测试用例

在dh.test.ts中

    const getDataFromRequest = require("./dh");
import { MockProxy, mock } from 'jest-mock-extended';

describe('test cases', () => {

  var inputReq = {
    params: {
      body: {
        "d_id": "733439150857912479",
        "last_access": "today",
        "user": "TestUser"
      }
    }
  }
  
  var getDataResult = {
    dName: "drw_733439150857912479",
    requestData: { "d_id": "733439150857912479", "last_access": "today", "user": "TestUser" },
    dColName: "SD-733439150857912479"
  }

  let mockResp: MockProxy<CbServer.Resp>;
  beforeEach(() => {
    mockResp = mock<CbServer.Resp>();
  });
  
  test('request with valid parameter', () => {    
      
    var resultData = getDataFromRequest(inputReq, mockResp);    
    expect(resultData).toEqual(getDataResult);
    expect(mockResp.error).toBeCalledTimes(0);
   
  });

  test('density hook request with invalid parameter', () => {    
          
    var resultData = getDataFromRequest(null, mockResp);
    //Argument of type '"error"' is not assignable to parameter of type 'never'.
    //mockResp.error.mockReturnValue("error");    
    mockResp.error.mockImplementation()
    expect(resultData).toBeFalsy();
    expect(mockResp.error).toHaveBeenCalled(); 
    //expect(mockResp.error).toEqual("error");
    
  });
})

我们如何测试错误消息字符串?即在dh.js中,我们返回resp.error(“ error”)我想测试此函数返回的消息。有什么方法可以测试消息?我尝试模拟返回值,但是它的类型从不表明我无法设置该值。

0 个答案:

没有答案