【问题标题】:How to set local storage in TestCafe before the page initialization页面初始化前如何在TestCafe中设置本地存储
【发布时间】:2021-06-28 16:45:47
【问题描述】:

在 Testcafe 初始化页面之前,我需要设置本地存储以绕过登录屏幕。我尝试注入自定义脚本,但这不起作用。

有人可以帮我怎么做吗?

【问题讨论】:

    标签: e2e-testing testcafe


    【解决方案1】:

    我尝试在 beforeEach 中设置本地存储项,但在我的情况下,我发现它设置得太晚了,无法满足我的需要。通过使用clientScripts 函数,我能够让事情正常进行。所以,它看起来像这样:

    fixture(`My tests`)
      .page("https://www.my-test-url.com")
      .clientScripts({
        content: 'window.localStorage.setItem("myKey", "myValue");'
      });
    

    【讨论】:

      【解决方案2】:

      要在 TestCafe 会话中设置本地存储变量,您可以使用ClientFunction's。您可以在 beforeEach 钩子中使用您的键设置本地存储变量,以便在您的每一个测试之前调用它。实现这一点的代码如下所示:

      const setLocalStorageItem = ClientFunction((key: string, value: string) => window.localStorage.setItem(key, value));
      
      fixture(`My tests`)
        .page("https://www.my-test-url.com")
        .beforeEach(async (t) => {
          await setLocalStorageItem("myLocalStorageKey", "myValue");
        });
      
      test('Some test', async (t) => {
        // This assertion should be fine for every test
        await t.expect(await getLocalStorageItem("myLocalStorageKey")).eql("myValue");
      
        // more test code should follow here
      })
      
      

      当 TestCafe 清除 localStorage and sessionStorage after each test 时,如果您想在每个测试中访问相同的本地存储键/值对(或者出于某种原因需要为每个测试设置它),您需要这样做。

      如果您希望仅为特定测试设置本地存储条目,您可以按照以下步骤进行:

      test('Some other test', async (t) => {
      
        // my test code
      }).before(async (t) => {
        await setLocalStorageItem("testKey", "testValue");
      });
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-10
        • 2019-01-18
        • 2021-03-10
        • 2014-04-10
        • 2015-03-10
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        相关资源
        最近更新 更多