การติดตั้งและใช้งาน Cypress แบบ TypeScript จนถึงการรัน มีขั้นตอนดังนี้:
mkdir my-cypress-project
cd my-cypress-project
npm init -y
ติดตั้ง Cypress ผ่าน npm:
npm install cypress --save-dev
ติดตั้ง TypeScript และ dependencies ที่เกี่ยวข้อง:
npm install typescript @tsconfig/node16 @types/node --save-dev
สร้างไฟล์ tsconfig.json
:
npx tsc --init
ตั้งค่าในไฟล์ tsconfig.json
เช่น:
{
"compilerOptions": {
"target": "ES6",
"lib": ["es6", "dom"],
"types": ["cypress"],
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["cypress/**/*.ts"]
}
เพื่อรองรับการใช้ TypeScript:
npm install @types/cypress --save-dev
รันคำสั่งนี้เพื่อเปิด Cypress GUI:
npx cypress open
Cypress จะสร้างโฟลเดอร์ cypress
และไฟล์การตั้งค่าชื่อ cypress.config.js
หรือ cypress.config.ts
(ถ้าต้องการใช้ TypeScript)
เปลี่ยนชื่อไฟล์ cypress.config.js
เป็น cypress.config.ts
และแก้ไขเนื้อหาให้เป็น TypeScript:
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
baseUrl: 'http://localhost:3000', // หรือ URL ของแอปพลิเคชันที่ต้องการทดสอบ
specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}', // รองรับไฟล์ TypeScript
},
});
สร้างไฟล์ตัวอย่างใน cypress/e2e/example.cy.ts
:
describe('My First Test', () => {
it('Visits the Kitchen Sink', () => {
cy.visit('https://example.cypress.io');
cy.contains('type').click();
cy.url().should('include', '/commands/actions');
cy.get('.action-email').type('[email protected]').should('have.value', '[email protected]');
});
});
npx cypress open
npx cypress run
To use cypress-xpath
in your Cypress project with TypeScript, follow these steps:
Run the following command to install the package:
npm install cypress-xpath
In the cypress/support/e2e.js
or cypress/support/e2e.ts
file (depending on your project setup), add this line to include cypress-xpath
:
require('cypress-xpath');
For TypeScript, you might use the ES module syntax:
import 'cypress-xpath';
To use TypeScript with cypress-xpath
, you'll need type definitions. Add the following line to your tsconfig.json
under compilerOptions
> types
:
{
"compilerOptions": {
"types": ["cypress", "cypress-xpath"]
}
}
You can now use cy.xpath()
in your test files. Here's an example:
describe('XPath Example', () => {
it('finds an element using XPath', () => {
cy.visit('https://example.com');
cy.xpath('//button[text()="Click Me"]').click();
});
});
Run your Cypress tests to ensure cy.xpath
is available and functioning correctly.
That's it! You should now be able to use XPath in your Cypress TypeScript project.