简体   繁体   English

测试从DOB计算年龄的函数

[英]Testing an function that calculates age from dob

I have a simple function in Javascript; 我在Javascript中有一个简单的函数;

  export default function getPupilAge(dob) {
  let a = moment();
  let b = moment(dob);
  return a.diff(b, 'months');
};

I am trying to write tests (I am using AVA). 我正在尝试编写测试(我正在使用AVA)。

I would like to write a test that says 'given a date returns 23 months' but the let a = moment(); 我想编写一个测试,说“给定日期返回23个月”,但是let a = moment(); is always today's date so the returned number of months will change over time. 始终是今天的日期,因此返回的月数会随着时间而变化。

How do I write this test, or refactor my function to allow testability? 如何编写此测试,或重构我的功能以允许可测试性?

Your function seems to calculate age in months (it uses diff from moment() with 'months' parameter), so you can pass moment().subtract(23, 'month'); 您的函数似乎以月为单位计算年龄(它使用来自带有'months'参数的moment() diff ),因此您可以传递moment().subtract(23, 'month'); that is the current date minus 23 months (see subtract docs). 那是当前日期减去23个月(请参阅subtract文档)。 In this case getPupilAge will always be 23 . 在这种情况下, getPupilAge将始终为23

Here a live example: 这是一个实时示例:

 function getPupilAge(dob) { let a = moment(); let b = moment(dob); return a.diff(b, 'months'); }; let dob = moment().subtract(23, 'month'); console.log(getPupilAge(dob)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 

You can use sinon to fake the date and time. 您可以使用sinon伪造日期和时间。
eg 例如

import test from 'ava';
import sinon from 'sinon';

function getPupilAge(dob) {
  let a = moment(); // here the date will be 2016-12-01T06:00:00.000Z
  let b = moment(dob); //here the date will be what you have specified in dob
  return a.diff(b, 'months');
}

test('fake dates', t => {
    sinon.useFakeTimers(new Date(2016,11,1).getTime());

    const result = getPupilAge("20170620");

    t.is(result,6) //example


});

In your function when you call moment() you will get the fake date. 在函数中,当您调用moment()时,您将得到假日期。

您可以随时let day = moment("1995-12-25");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM