Jest: toHaveBeenCalled возвращает 0 вместо 1 - PullRequest
0 голосов
/ 07 мая 2020

У меня есть функция, называемая трекером ликвидации, которая делает что-то вроде:

// liquidation_tracker.js file
async function liquidation_tracker(sendSms) {
  const requires_notification = [1,2,3] // some dummy data
  if (requires_notification.length > 0 && sendSms) {
        sendNotification(requires_notification)
    }
}

async function sendNotification() {
  return null // assume it sends an sms
}

Тестовый код, который я пытался сделать, это

const liquidation_tracker = require('./liquidation_tracker);
liquidation_tracker.sendNotification = jest.fn();
it('should notify if margin ratio is > 0.8', async () => {
    const check = await liquidation_tracker.checkLiquidation(true);
    expect(liquidation_tracker.sendNotification).toHaveBeenCalled();
})

Но это возвращается 0 вместо 1

1 Ответ

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

Вам необходимо убедиться, что на фиктивную функцию sendNotification есть та же ссылка, что и на функцию sendNotification, вызываемую внутри функции checkLiquidation.

Например

liquidation_tracker.js:

async function checkLiquidation(sendSms) {
  const requires_notification = [1, 2, 3];
  if (requires_notification.length > 0 && sendSms) {
    exports.sendNotification(requires_notification);
  }
}

async function sendNotification() {
  return null;
}

exports.checkLiquidation = checkLiquidation;
exports.sendNotification = sendNotification;

index.test.js:

const liquidation_tracker = require('./liquidation_tracker');

describe('61657292', () => {
  it('should notify if margin ratio is > 0.8', async () => {
    const sendNotificationMock = jest.fn();
    liquidation_tracker.sendNotification = sendNotificationMock;
    await liquidation_tracker.checkLiquidation(true);
    expect(sendNotificationMock).toHaveBeenCalled();
  });
});

результаты модульного тестирования с отчетом о покрытии:

 PASS  stackoverflow/61657292/liquidation_tracker.test.js (12.385s)
  61657292
    ✓ should notify if margin ratio is > 0.8 (4ms)

------------------------|---------|----------|---------|---------|-------------------
File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------------------|---------|----------|---------|---------|-------------------
All files               |   83.33 |       75 |      50 |   83.33 |                   
 liquidation_tracker.js |   83.33 |       75 |      50 |   83.33 | 9                 
------------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.201s
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...