为遵循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
_baseLoginmethod handles all repetitive steps that both login flows share—waiting for the page to load, entering credentials, clicking submit. Returningthiskeeps Nightwatch's method chaining intact, which is critical for these command sequences. - Simplified specific methods:
loginAdminandloginMembernow 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_baseLoginonce 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
相关产品推荐
相关产品推荐

