开玩笑:toHaveBeenCalled返回0而不是1

时间:2020-05-07 12:02:41

标签: javascript unit-testing jestjs

我有一个称为清算跟踪器的功能,它可以执行以下操作:

// 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 :(得分:0)

您需要确保模拟的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