You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为遵循DRY原则重构代码失败,请求技术解决方案

Refactoring Login Commands to Follow DRY Principle

Great catch noticing the redundant code here—DRYing this up will make your tests way easier to maintain down the line. Let's fix that refactor by extracting the shared login logic into a reusable helper method, then building the admin/member-specific steps on top of it.

Here's the cleaned-up version of your code:

const loginCommands = {
  // Shared base login logic (private helper convention with underscore)
  _baseLogin: function(email, password) {
    return this.waitForElementVisible('body', 1000)
      .setValue('@email', email)
      .setValue('@password', password)
      .click('@submit');
  },

  loginAdmin: function(email, password) {
    return this._baseLogin(email, password)
      .waitForElementVisible('@adminMainMenu', 1000)
      .verify.attributeEquals('@adminMainMenu', 'data-role', 'admin');
  },

  loginMember: function(email, password) {
    return this._baseLogin(email, password)
      // Add your member-specific post-login checks here
      .waitForElementVisible('@memberMainMenu', 1000) // Example member element
      .verify.attributeEquals('@memberMainMenu', 'data-role', 'member'); // Example verification
  }
};

Key changes explained:

  • Extracted shared logic: The _baseLogin method handles all repetitive steps that both login flows share—waiting for the page to load, entering credentials, clicking submit. Returning this keeps Nightwatch's method chaining intact, which is critical for these command sequences.
  • Simplified specific methods: loginAdmin and loginMember now only handle the unique parts of each flow (the post-login verification). This means if you ever need to update the core login process (like changing a selector or adjusting wait times), you only have to edit _baseLogin once instead of duplicating changes across both functions.
  • Private helper convention: The underscore prefix (_baseLogin) signals this is an internal helper method, not meant to be called directly from your test cases.

If your initial refactor failed, it was likely because you didn't preserve the command chain by returning this from the helper, or didn't structure the calls to build on the shared logic properly. This approach fixes both issues while fully adhering to the DRY principle.

内容的提问来源于stack exchange,提问作者Madeline Ries

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:41:33