【问题标题】:Jest: Mock class method in a function笑话:函数中的模拟类方法
【发布时间】:2020-05-07 04:13:50
【问题描述】:

所以只是想了解我如何在函数本身中模拟类函数。如何模拟从 exchange.someFunction() 方法返回的数据,以便测试实际的 getPositions() 函数本身?

const library = require('library');
const exchange = new library.exchange_name();

async function getPositions() {

    let positions = [];

    const results = await exchange.someFunction();
    // Do some stuff
    return results;

}

我正在尝试执行以下操作,但不知道我做的是否正确

const exchange = require('../../exchange');
jest.mock('library')

it('get balances', async () => {
    library.someFunction.mockResolvedValue({
        data: [{some data here}]
   )}
}

抛出错误:

TypeError: Cannot read property 'mockResolvedValue' of undefined

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    这里是单元测试解决方案:

    index.js:

    const library = require('./library');
    const exchange = new library.exchange_name();
    
    async function getPositions() {
      let positions = [];
    
      const results = await exchange.someFunction();
      return results;
    }
    
    module.exports = getPositions;
    

    library.js:

    function exchange_name() {
      async function someFunction() {
        return 'real data';
      }
    
      return {
        someFunction,
      };
    }
    
    module.exports = { exchange_name };
    

    index.test.js:

    const getPositions = require('./');
    const mockLibrary = require('./library');
    
    jest.mock('./library', () => {
      const mockExchange = { someFunction: jest.fn() };
      return { exchange_name: jest.fn(() => mockExchange) };
    });
    
    describe('61649788', () => {
      it('get balances', async () => {
        const mockExchange = new mockLibrary.exchange_name();
        mockExchange.someFunction.mockResolvedValueOnce({ data: ['mocked data'] });
        const actual = await getPositions();
        expect(actual).toEqual({ data: ['mocked data'] });
        expect(mockExchange.someFunction).toBeCalled();
      });
    });
    

    100% 覆盖率的单元测试结果:

     PASS  stackoverflow/61649788/index.test.js (8.775s)
      61649788
        ✓ get balances (7ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     index.js |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        10.099s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多