【问题标题】:Run custom JavaScript in Chromium with CodeceptJS?使用 CodeceptJS 在 Chromium 中运行自定义 JavaScript?
【发布时间】:2020-02-07 02:57:05
【问题描述】:

我需要模拟 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 Monkey 中的代码修补了日期:

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

这些都不会对日期产生任何影响。

【问题讨论】:

    标签: codeceptjs


    【解决方案1】:

    问题是 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();
    

    希望这有助于@:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2021-07-03
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多