0% found this document useful (0 votes)
42 views17 pages

OrangeLogic Online Test

The document covers various coding challenges and concepts related to Cypress and Postman, including automated testing with Cypress, handling asynchronous operations, and dynamically setting variables in Postman. It provides code examples and explanations for creating a toggle button in React, inspecting elements during Cypress tests, and configuring test retries. Additionally, it distinguishes between Cypress commands like '.get()' and '.find()', and outlines the purpose of the 'cy.get()' function.

Uploaded by

Bryant Duong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views17 pages

OrangeLogic Online Test

The document covers various coding challenges and concepts related to Cypress and Postman, including automated testing with Cypress, handling asynchronous operations, and dynamically setting variables in Postman. It provides code examples and explanations for creating a toggle button in React, inspecting elements during Cypress tests, and configuring test retries. Additionally, it distinguishes between Cypress commands like '.get()' and '.find()', and outlines the purpose of the 'cy.get()' function.

Uploaded by

Bryant Duong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Contents

Bash challenge..........................................................................................1
Front-end challenge..................................................................................3
In cypress, how can you inspect the elements of a page during a
test?............................................................................................................5
How does cypress handle asynchronous operations ?.......................6
In Cypress, how can you make a test retry when it fails?.................7
In Cypress, what's the fifference between '.get()' and '.find()'
commands ?...............................................................................................9
In Cypress, what is the purpose of the 'cy.get()' function ?............10
In Postman, how can you dynamically set the value of a variable in
a script ?...................................................................................................12
In Postman, how can you prameterize requests for dynamic data
usage.........................................................................................................13
How can you validate the response structure in Postman tests?. .14
In Postman, what is the primary purpose of scripting tests in the
Pre-request Script tab?..........................................................................16
What is Load Testing in the context of web applications ?.............16
What does Jmeters’ Listener element do?..........................................16
How can you simulate of threads in the Thread Group....................17

Bash challenge
In the bash script, write a simple automated test named cypressTest.js thay
does the following:
Use the describe and it functions to create a test.
Use the Cypress visit function to visit https://coderbyte.com/profile (wrapped
in single quotes).
Use contains to find an element with the keyword settings and click the
element. And finally use should to make sure thr new URL includes the
keyword /settings

Solution:
// cypressTest.js

describe('Coderbyte Profile Test', () => {

it('Should navigate to settings page', () => {

cy.visit('https://coderbyte.com/profile');

cy.contains('Settings').click();

cy.url().should('include', '/settings');

});

});

Explanation:

1. describe('Coderbyte Profile Test', ...): This sets up a test suite with


a descriptive name.

2. it('Should navigate to settings page', ...): This defines a single


test case within the suite.

3. cy.visit('https://coderbyte.com/profile');: This tells Cypress to visit


the specified URL.

4. cy.contains('Settings').click();: This:

o Finds the first element on the page containing the text


"Settings".

o Clicks on that element, simulating a user interaction.

5. cy.url().should('include', '/settings');: This asserts that the URL


after the click includes "/settings", verifying successful navigation.

To Run This Test:

1. Prerequisites:

o Ensure you have Node.js and npm (or yarn) installed.

o Have a Cypress project set up (if not, follow Cypress's getting


started
guide: https://docs.cypress.io/guides/getting-started/installing-
cypress).

2. Place cypressTest.js: Put this file inside your Cypress integration


folder (usually cypress/e2e or similar).

3. Run Cypress: Use the command npx cypress open or yarn cypress
open in your terminal to open the Cypress Test Runner.

4. Select the Test: Choose "cypressTest.js" from the list of available


tests to run it.

Cypress will execute the test in a real browser, providing visual feedback and
detailed logs about each step.

Front-end challenge
We provided some simple React+typeScript template code. Your goal is to
modify the component so that you can properly toggle the button to switch
between an ON state and an OFF state. When the button is on and it is
clicked, it turn off and the text within it changed from ON to OFF vice versa.
Make use of component state for this challenge.
You are free to add classes and styles, but make sure you leave the
component ID's and classes provided as they are. Submit your code once it is
complete and our system will validate your output.
import React, {useState} from 'react';
import {createRoot} from 'react-dom/client';

function Toggle() {
function handleClick() {
//todo
}

return (
<button>ON<button/>
}
}

const container = document.getElementById('root');


const root = createRoot(container);
root.render(<Toggle />);

Solution:
import React, { useState } from 'react';

import { createRoot } from 'react-dom/client';

function Toggle() {

const [isOn, setIsOn] = useState(true);

const handleClick = () => {

setIsOn(!isOn);

};

return (

<button onClick={handleClick}>

{isOn ? 'ON' : 'OFF'}

</button>

);

const container = document.getElementById('root');

const root = createRoot(container);

root.render(<Toggle />);

Explanation:

1. Import useState: We import the useState hook from React to manage


the button's state.

2. State Initialization:

o const [isOn, setIsOn] = useState(true); creates a state


variable isOn and initializes it to true, indicating the button starts
in the "ON" state.

3. handleClick Function:
o setIsOn(!isOn); toggles the state
of isOn between true and false each time the button is clicked.

4. Conditional Rendering:

o Inside the button element, we use a ternary operator (condition ?


trueValue : falseValue) to conditionally render the button text:

 If isOn is true (button is ON), display "ON".

 If isOn is false (button is OFF), display "OFF".

How it Works:

 The component starts with the button in the "ON" state (isOn is true).

 When the button is clicked:

o The handleClick function is called.

o setIsOn(!isOn) flips the value of isOn.

o React re-renders the component, and the button's text updates


to reflect the new state.

Now, clicking the button will correctly toggle it between the "ON" and "OFF"
states.

In cypress, how can you inspect the elements of a


page during a test?
1. Using the cypress Test Runner's 'Open Selector Playground' option

2. Using browser's developer tools after test completion

3. Running a special inpect() command

4. writing custom javascript functions

Here's the breakdown of how to inspect elements in Cypress, along with the
best options:

Best Options:

 1. Using the Cypress Test Runner's 'Open Selector Playground'


option: This is the most recommended and efficient way to
inspect elements in Cypress.
o How: When you're in the Cypress Test Runner, hover over any
test step that interacts with the DOM. You'll see a crosshair icon.
Click it, and Cypress will open the Selector Playground, providing
you with suggested selectors for the element you targeted.

 2. Using browser's developer tools during test execution


(with cy.pause() or breakpoints): This method allows you to pause
your test execution and use the familiar developer tools for inspection.

o How:

 cy.pause(): Add cy.pause() within your test code where


you want the execution to halt. You can then freely use
your browser's dev tools.

 Breakpoints: Set breakpoints directly within your test


code in the Cypress Test Runner. When the breakpoint is
hit, execution pauses.

Less Ideal (and Why):

 3. Running a special inspect() command: Cypress doesn't have a


dedicated inspect() command. The Selector Playground offers a more
streamlined inspection workflow.

 4. Writing custom JavaScript functions: While you could write


custom functions to grab element information, it's generally
unnecessary. Cypress's built-in commands and the Selector Playground
provide much simpler ways to achieve the same results.

Key Advantages of the Cypress Test Runner and Selector


Playground:

 Real-time Feedback: See the effects of your selectors immediately


as you interact with the page.

 Automatic Selector Generation: Cypress suggests efficient and


robust selectors for you.

 Seamless Integration: Inspection is tightly integrated into the test


runner, making your workflow smooth.
How does cypress handle asynchronous operations
?
1. Cannot handle asynchronous operations

2. Runs all commands immediately without waiting

3. Automatically waits for commands and assertions before moving on


the next step

4. Requires explicit wait commands for each asynchronous operation

The correct answer is 3. Automatically waits for commands and


assertions before moving on to the next step.

Here's why:

 Cypress's Core Strength: One of Cypress's most powerful features is


its built-in handling of asynchronous operations. Unlike other testing
frameworks that often require explicit waits or complex promise
handling, Cypress manages this for you behind the scenes.

 How Cypress Does It:

o Command Queue: Cypress chains all your commands together


and places them in a queue.

o Automatic Retries: Before executing a command, Cypress


waits for the previous command and any associated assertions to
resolve. It also has built-in retries for actions like finding
elements or waiting for network requests.

o Promises Under the Hood: Cypress utilizes Promises internally


to manage asynchronous behavior, but you usually don't need to
interact with them directly.

Example:

cy.visit('/users'); // Cypress waits for the page to load

cy.get('.user-list li').should('have.length', 5); // Waits for the list to have 5


items

cy.get('.user-list li:first').click(); // Waits for the first item to be clickable and


then clicks it
In this example, Cypress automatically handles the asynchronous nature of
loading the page, finding elements, and waiting for them to be in the correct
state before proceeding to the next command.

Let me know if you'd like more details or examples of Cypress's


asynchronous handling!

In Cypress, how can you make a test retry when it


fails?
1. By configuring the 'retries' option in the Cypress configuration file

2. By using the cy.retry() command

3. Cypress does not support test retries

4. by wrapping the test code in a try-catch block

The correct answer is 1. By configuring the 'retries' option in the


Cypress configuration file.

Here's a breakdown:

 1. Cypress Configuration
(cypress.config.js or cypress.config.ts): This is the recommended
and most flexible way to handle retries in Cypress. You can configure
retries globally or for specific tests and test suites:

 // cypress.config.js

 module.exports = defineConfig({

 e2e: {

 // Globally retry all specs 2 times

 retries: 2,

 // Retry specific specs within a suite

 setupNodeEvents(on, config) {

 on('before:spec', (spec) => {

 if (spec.relative.includes('flaky_test.cy.js')) {
 spec.retries = 3; // Retry this specific spec 3 times

 }

 });

 // Or set retries based on tags

 on('before:run', (details) => {

 if (details.tag.includes('flaky')) {

 details.retries = 4; // Retry tagged specs 4 times

 }

 });

 },

 },

});

 2. cy.retry() (Deprecated): This command existed in older Cypress


versions but is now deprecated and no longer recommended. The
configuration file provides more control and cleaner test code.

 3. Cypress does support test retries: This statement is incorrect,


as shown by the explanation above.

 4. try-catch blocks: These are designed for handling synchronous


JavaScript errors and aren't suitable for handling asynchronous test
failures, which Cypress manages with its retry mechanism.

Key Points:

 Use retries cautiously: While retries can help with flaky tests, it's
crucial to investigate and fix the root cause of flakiness rather than
solely relying on retries.

 Consider the trade-off: Retries increase test execution time. Use


them strategically for tests that are genuinely flaky.

Let me know if you have any other questions about retries or other Cypress
features!
In Cypress, what's the fifference between '.get()'
and '.find()' commands ?
1. '.get()' selects elements globally, whereas '.find()' select child element
of a specific parent

2. '.get()' and '.find()' perform the same action

3. '.find()' is a deprecated command that has been replaced by '.get()'

4. '.get()' select child elements, whereas '.find()' select elements globally

The correct answer is 1. '.get()' selects elements globally, whereas


'.find()' selects a child element of a specific parent.

Here's a breakdown:

 cy.get():

o Purpose: Selects elements within the entire document based on


a CSS selector.

o Scope: Global - searches the entire DOM tree from the root.

o Example: cy.get('button') - finds all button elements on the


page.

 cy.find():

o Purpose: Selects elements that are descendants (children,


grandchildren, etc.) of a previously yielded Cypress chain.

o Scope: Local - searches within the elements yielded by the


preceding command.

o Example:

o cy.get('.todo-list') // Get the todo list element

.find('li') // Find all list items within the todo list

content_copyUse code with caution.JavaScript

In simpler terms:

 Use cy.get() to start your search from the top of the page and find
elements anywhere in the DOM.
 Use cy.find() to narrow down your search within a specific section or
parent element that you've already selected.

Important Note: cy.find() needs to be chained after a command that yields


a DOM element. This could be cy.get(), cy.contains(), or another command
that returns DOM elements.

In Cypress, what is the purpose of the 'cy.get()'


function ?
1. to query elements in the DOM

2. to get a previously stored item from Local Storage

3. to navigate to a specific URL

4. to fetch data from a server

The correct answer is 1. to query elements in the DOM.

Here's why:

 cy.get() is fundamental to Cypress: It's the primary way to interact


with the elements on your web page during testing.

 How it works:

o You provide cy.get() with a CSS selector as an argument.

o Cypress then searches the DOM (Document Object Model) to find


all elements that match the selector.

o cy.get() returns a Cypress chainable object that represents the


selected element(s), allowing you to perform actions or
assertions on them.

Example:

cy.get('#username') // Finds an element with the ID "username"

.type('myusername'); // Types "myusername" into the found input field

content_copyUse code with caution.JavaScript

Let's clarify the other options:

 2. Local Storage: To work with Local Storage, Cypress provides


specific commands like:
o cy.clearLocalStorage()

o cy.setLocalStorage()

o cy.getLocalStorage()

 3. Navigation: Use cy.visit() to navigate to a URL:

o cy.visit('https://www.example.com')

 4. Fetching data: Use cy.request() to make network requests and get


data from a server.

o cy.request('GET', '/api/users').then(response => {...})

Let me know if you have any other Cypress questions!

In Postman, how can you dynamically set the value


of a variable in a script ?
1. by editing the collection JSON

2. through the environment quick look

3. using the pm/environment.set() function

4. variables cannot be set dynamically

The correct answer is 3. using the pm.environment.set() function.

Here's why:

 pm.environment.set() is a Postman scripting function specifically


designed to create or update environment or global variables
dynamically within your request scripts.

Example:

// Set a variable named 'userId' with a random value

pm.environment.set('userId', Math.floor(Math.random() * 1000));

// Access the variable in your request

let url = `https://api.example.com/users/${pm.environment.get('userId')}`;

content_copyUse code with caution.JavaScript


Let's look at the other options:

 1. Editing the collection JSON: This is not a recommended way to


dynamically set variables. Directly editing the JSON is prone to errors
and makes your collection less maintainable.

 2. Environment quick look: The quick look feature allows you to


view and temporarily edit variable values, but these changes are not
persistent and will not be saved.

 4. Variables cannot be set dynamically: This statement is


incorrect. Postman's scripting capabilities are designed for dynamic
behavior.

Key Points:

 Scope: You can use pm.environment.set() to set both environment and


global variables.

 Dynamic Data: This function is very useful for working with random
values, timestamps, data from responses, and more.

Let me know if you'd like to see more examples or have other Postman
scripting questions!

In Postman, how can you prameterize requests for


dynamic data usage
1. using variables

2. using external files

3. hardcoding values

4. API gateway

The correct answer is 1. using variables.

Here's why:

1. Using Variables: This is the most common and efficient way to


parameterize requests in Postman.

 How it works:

o Define Variables: You can define variables at different scopes


(global, collection, environment) to hold your dynamic values.
o Access in Requests: Use the variable syntax
({{variableName}}) to insert variable values into your request
URLs, headers, body parameters, and even pre-request and test
scripts.

 Example:

 GET https://api.example.com/users/{{userId}}

// Where `userId` is a variable defined in your environment or collection.

The other options are less suitable for this specific purpose:

 2. Using external files: While you can load data from external files,
this approach is often used for data-driven testing, where you want to
run the same request with multiple sets of data.

 3. Hardcoding values: Hardcoding makes your requests inflexible


and difficult to maintain. It's the opposite of parameterization.

 4. API Gateway: API gateways are used for managing, routing, and
securing API requests, not directly for parameterizing requests within
Postman.

Why Variable Parameterization is Crucial:

 Reusability: Use the same requests with different data by simply


changing variable values.

 Maintainability: Update values in one place (environment or


collection variables) instead of searching and replacing throughout
your requests.

 Dynamic Behavior: Create more realistic and flexible tests by using


random data, timestamps, or values extracted from previous
responses.

Key Takeaways:

 Prioritize variables: Always look to leverage variables first when you


need to introduce dynamic data into your Postman requests.

 Explore variable scopes: Understand the differences between


global, collection, and environment variables to choose the most
appropriate scope for your use case.
How can you validate the response structure in
Postman tests?
1. using javascript assertions on the response object
2, using external validation tools

2. reponse structure cannot be validated

3. by vusually inspecting the response

The correct answer is 1. using JavaScript assertions on


the pm.response object.

Here's a breakdown:

 Postman Tests: Postman's built-in testing sandbox uses JavaScript


and the pm API (specifically the pm.response object) to interact with
your responses and perform assertions.

 Validating Response Structure with Assertions:

 pm.test("Validate response structure", function () {

 const jsonData = pm.response.json(); // Parse JSON response

 pm.expect(jsonData).to.have.property('status');

 pm.expect(jsonData.status).to.be.a('string');

 pm.expect(jsonData).to.have.property('data');

 pm.expect(jsonData.data).to.be.an('array');

 pm.expect(jsonData.data[0]).to.have.property('id');

 pm.expect(jsonData.data[0].id).to.be.a('number');

 // ... more assertions ...

});

content_copyUse code with caution.JavaScript


o This code snippet checks for the presence of specific properties,
their types (string, array, number), and even dives into nested
objects within the response.

 Let's look at the other options:

o 2. Using external validation tools: While


you could technically send your response data to an external
tool, it's less efficient and introduces unnecessary complexity
when Postman offers robust built-in validation.

o 3. Response structure cannot be validated: This statement


is incorrect. Validating structure is a fundamental part of API
testing.

o 4. By visually inspecting the response: Visual inspection is


good for initial checks but unreliable and not scalable for
automated tests.

Key Benefits of Using Postman Assertions:

 Automated Validation: Integrate structure checks into your


automated API tests for continuous validation.

 Early Issue Detection: Catching structural issues early in the


development process prevents larger problems down the line.

 Clear and Concise Tests: Assertions make your tests more readable
and easier to maintain.

Let me know if you'd like to see more advanced examples of response


validation, such as using JSON Schema validation within Postman!

In Postman, what is the primary purpose of


scripting tests in the Pre-request Script tab?
1. To execute logic before a request is sent

2. To modify the response body

3. To create new API endpoints

4. To generate reports after the request


What is Load Testing in the context of web
applications ?
1. A testing process that identifies the maximum operation capacity of an
application

2. Testing the system with an unexpected amount of data

3. A type of testing that check how a system operates under minimal load

4. A type of performance testing that checks how a system operates under


an expected load

What does Jmeters’ Listener element do?


1. Collects and displays test results

2. Configures database connections

3. Send HTTP requests

4. Sets up preconditions for a test

How can you simulate of threads in the Thread


Group
1. By Setting number of threads in the Thread Groups

2. Using a Sampler

3. Using a Listener

4. By Creating multiple test plans

You might also like