运行 使用 CodeceptJS 在 Chromium 中自定义 JavaScript?

Run custom JavaScript in Chromium with CodeceptJS?

我需要为我的 CodeceptJS 测试模拟时间。

我的 React 组件使用 new Date() 函数:

const Component = () => {
    console.log(new Date())
    return <h1>Im a component</h1>
}

我需要组件认为它是 2018 年。对于我的 Jest 单元测试,这很简单:

import MockDate from 'mockdate';

MockDate.set('2018-10');

test("test something", ()=>{
    // Actual test here 
})

MockDate.reset(); 

我怎样才能用 CodeceptJS 做同样的事情?我尝试在测试中使用日期模拟模块:

Scenario('@test', async (CheckoutPage) => {
    const MockDate = require('mockdate');
    MockDate.set('2018-10');
     // Actual test here

});

我也试过依赖注入。 FIX-DATE 猴子中的代码修补了日期:

Scenario(
  '@test',
  (CheckoutPage, FixDate) => {
    FixDate();
    CheckoutPage.load();
    pause();
  }
).injectDependencies({ FixDate: require('./FIX-DATE') });

这些都不会影响日期。

问题是 CodeceptJS 在浏览器中 运行,所以你需要覆盖浏览器的日期对象。

基本上你需要覆盖浏览器的日期对象,或者使用的函数,例如:

// create a date object for this Friday:
var d = new Date(2018, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};

var now = new Date()
console.log(now);

Date.now = function () { return d};
console.log(Date.now());

这是纯JS的方式,第二步是集成到codeceptjs,可以使用I.executeScript

例如:

  I.executeScript(function () {
    var d = new Date(2018, 0, 20);
    Date = function(){return d;};
  })

您还可以创建自定义步骤,例如,I.fakeDate(new Date(2018, 0, 20))

    module.exports = function() {
      return actor({

        fakeDate: function(date) {

             I.executeScript(function (fakeDate) {
                 var d = fakeDate;
                 window.__original_date = Date;
                 Date = function(){return d;};
             }, date);
        },

        fakeDateRestore: function() {
            I.executeScript(function () {
                 Date = window.__original_date;
            });
        }

      });
    }

然后你只需要在需要的时候伪造日期,然后恢复它。

I.Click('beofre');
I.fakeDate(new Date(2018,10,01));
// The test code here
I.fakeDateRestore();

希望这对您有所帮助@:-)