为什么 jest mocked 函数没有 return 任何东西?

why jest mocked function doesnt return anything?

我要测试的代码是

    'use strict';

const FastestValidator = require("fastest-validator");
const { selector } = require("../selector");

/**
 * @param {object} data - Request Body object
 * @return {object} - Valiated results after applying the Schema
 *
 **/

const validator = async (data) => {
  try {
    console.log("FastestValidator>>  ",FastestValidator)
    console.log("selector>>  ",selector)
    const v = new FastestValidator();
    let schema = await selector(data);
    console.log("schema>>  ",schema)
    console.log("v>>  ",v)
    let check = v.compile(schema);
    let inBoundMappedSchema = {};
    let validatingInboundData = {};


    for (let index in schema) {
      inBoundMappedSchema[index] = data[index];
    }
    validatingInboundData = await check(inBoundMappedSchema);
    if (typeof validatingInboundData === 'object') {
      return {
        success: false,
        potentialIssue: validatingInboundData
      }
    } else if (validatingInboundData && typeof boolean) {
      return {
        success: true,
      }
    }
  } catch (err) {
    console.log("error>>", err)
    return {
      success: false,
      errorMessage: err
    }
  }

};

module.exports = {
  validator
};

我的测试用例是..

    const {validator} = require('./index');

let FastestValidator = require("fastest-validator");
let { selector } = require("../selector");
jest.mock('../selector');
jest.mock('fastest-validator');






test('testing schema validator', async () => {
  let failed = {
    success: false,
    
  }
  let data = {
      message: 'you '
  }
  
  
  console.log("selector",selector)
  selector = jest.fn();
  selector.mockReturnValueOnce(data);

  selector.mockResolvedValue("randomPrivateKey")
  

  

  console.log("FastestValidator",FastestValidator)
  console.log("selector",selector)
  


  console.log("FastestValidator",validator.FastestValidator)
  console.log("selector",validator.selector)
  

  

    
      
    
    await expect(validator(data)).resolves.toEqual(failed);
  });

在调试日志中,我可以看到 schema>> 未定义,我想将其设为数据或 randomprivateKey。 如果我知道如何模拟使用 new 关键字创建的对象,我会非常有帮助,因为我正在使用 new FastestValidator() 来创建对象,我也需要模拟它的所有方法。

添加控制台输出:

    FAIL  src/api/schema/validator/index.test.js
  ● Console

    console.log
      selector [Function: selector] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)],
        constructor: [Function: AsyncFunction] {
          _isMockFunction: true,
          getMockImplementation: [Function (anonymous)],
          mock: [Getter/Setter],
          mockClear: [Function (anonymous)],
          mockReset: [Function (anonymous)],
          mockRestore: [Function (anonymous)],
          mockReturnValueOnce: [Function (anonymous)],
          mockResolvedValueOnce: [Function (anonymous)],
          mockRejectedValueOnce: [Function (anonymous)],
          mockReturnValue: [Function (anonymous)],
          mockResolvedValue: [Function (anonymous)],
          mockRejectedValue: [Function (anonymous)],
          mockImplementationOnce: [Function (anonymous)],
          mockImplementation: [Function (anonymous)],
          mockReturnThis: [Function (anonymous)],
          mockName: [Function (anonymous)],
          getMockName: [Function (anonymous)]
        }
      }

      at Object.<anonymous> (src/api/schema/validator/index.test.js:23:11)

    console.log
      FastestValidator [Function: Validator] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)]
      }

      at Object.<anonymous> (src/api/schema/validator/index.test.js:32:11)

    console.log
      selector [Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)]
      }

      at Object.<anonymous> (src/api/schema/validator/index.test.js:33:11)

    console.log
      FastestValidator undefined

      at Object.<anonymous> (src/api/schema/validator/index.test.js:37:11)

    console.log
      selector undefined

      at Object.<anonymous> (src/api/schema/validator/index.test.js:38:11)

    console.log
      FastestValidator>>   [Function: Validator] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)]
      }

      at validator (src/api/schema/validator/index.js:14:13)

    console.log
      selector>>   [Function: selector] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)],
        constructor: [Function: AsyncFunction] {
          _isMockFunction: true,
          getMockImplementation: [Function (anonymous)],
          mock: [Getter/Setter],
          mockClear: [Function (anonymous)],
          mockReset: [Function (anonymous)],
          mockRestore: [Function (anonymous)],
          mockReturnValueOnce: [Function (anonymous)],
          mockResolvedValueOnce: [Function (anonymous)],
          mockRejectedValueOnce: [Function (anonymous)],
          mockReturnValue: [Function (anonymous)],
          mockResolvedValue: [Function (anonymous)],
          mockRejectedValue: [Function (anonymous)],
          mockImplementationOnce: [Function (anonymous)],
          mockImplementation: [Function (anonymous)],
          mockReturnThis: [Function (anonymous)],
          mockName: [Function (anonymous)],
          getMockName: [Function (anonymous)]
        }
      }

      at validator (src/api/schema/validator/index.js:15:13)

    console.log
      schema>>   undefined

      at validator (src/api/schema/validator/index.js:18:13)

    console.log
      error>> TypeError: check is not a function
          at validator (/Users/h0j020h/amlng-realtime-api/src/api/schema/validator/index.js:27:35)
          at processTicksAndRejections (internal/process/task_queues.js:95:5)
          at Object.<anonymous> (/Users/h0j020h/amlng-realtime-api/src/api/schema/validator/index.test.js:46:5)

      at validator (src/api/schema/validator/index.js:39:13)

您需要以这种方式模拟 compile 方法和 selector

const FastestValidator = require("fastest-validator");
const { validator } = require('./validator')
const { selector } = require("../selector");

jest.mock('../selector');
jest.mock('fastest-validator');

const compile = jest.fn();

FastestValidator.mockImplementation(() => ({
  compile
}))

it('testing schema validator', async () => {
  let failed = {
    success: false,
    potentialIssue: {}
  };

  let data = {
      message: 'you ';
  }
  
  selector.mockResolvedValueOnce(data);
  // selector.mockResolvedValue("randomPrivateKey");
  const check = jest.fn();
  compile.mockReturnValue(check);
  check.mockResolvedValue({});
  await expect(validator(data)).resolves.toEqual(failed);
});

原始代码中的主要问题是 selector = jest.fn();,为什么?因为你在那行说现在选择器是一个模拟函数,没有任何绑定到 "../selector" 模块,所以当你调用 validator(data) 时,函数中的选择器是你不在其中的原始模拟模块没有 运行 那些方法 .mockReturnValueOnce(data).mockResolvedValue("randomPrivateKey"),而是你在 jest.fn() 指令中 运行 它们,该指令未绑定到被模拟的模块.

关于“mocking new”,new FastestValidator()只是创建了一个对象,里面有方法和属性,所以在测试代码中:

FastestValidator.mockImplementation(() => ({
  compile
}))

FastestValidator returns 一个对象,其中有一个名为 compile 的方法,该方法是一个模拟方法 jest.fn()