Шутка: метод фиктивного класса в функции - PullRequest
0 голосов
/ 07 мая 2020

Просто пытаюсь понять, как я имитирую функцию класса внутри самой функции. Как имитировать данные, возвращаемые методом 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;

}

Я пытался сделать следующее, но понятия не имею, ' m вообще что-то делает правильно

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

1 Ответ

0 голосов
/ 07 мая 2020

Вот решение для модульного теста:

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
...