start
1.1 install
cd /path/project
yarn add cypress --dev
1.2 open
npx cypress open
1.3 run
npx cypress run
simple test
但我們把project set up 好了之后,開始寫一個最簡單的test case 并且保證該測試可以運行起來。
describe('bing search', () => {
it('should work', () => {
cy.visit('https://cn.bing.com/');
cy.get('#sb_form_q')
.type('Hello world')
.type('{enter}')
.get('#b_content')
.contains('Hello world')
});
});
該用例描述的是打開bing然后輸入Hello world,查找,查找的結果需要包含Hello world。在該例子中在feature文件中將元素也寫在這里,接下來了解下Automation中常見的一種設計PO.
PO
關于PO,可以看這篇http://www.lxweimin.com/p/546c9dd166d3
pages
import * as Ids from '../../app/constants';
class LoginPage {
visit() {
cy.visit('https://test-th97479.slack.com/');
}
get EmailAddr() {
return cy.get(`#${Ids.emailAddr}`);
}
get Password() {
return cy.get(`#${Ids.password}`);
}
fillEmail(value: string){
const field = cy.get(`#${Ids.emailAddr}`);
field.clear();
field.type(value);
return this;
}
fillPassword(value: string){
const field = cy.get(`#${Ids.password}`);
field.clear();
field.type(value);
return this;
}
submit() {
const button = cy.get(`#${Ids.login}`);
button.click();
}
}
export const loginPage = new LoginPage();
features.ts
import {loginPage} from './pages/loginPage';
describe('page object', () => {
it('should work', () => {
loginPage.visit();
loginPage.fillEmail('summer.gan')
loginPage.fillPassword('test123');
loginPage.submit();
});
});
cypress中的command
對于e2e測試中,有很多相似的步驟比如登錄,輸入賬號密碼點擊登錄,通常來說我們可以把它抽象成一個方法。
export const login = (username: string, password: string) => {
cy.get('#email').type(username)
cy.get('#password').type(password)
cy.get('#signin_btn').click()
}
對與cypress而言還提供了一種command方式。
declare global {
namespace Cypress {
interface Chainable {
login:(email: string, password: string)=>Chainable<any>
}
}
}
export function login(email: string, password: string){
cy.get('#email').type(email)
cy.get('#password').type(password)
cy.get('#signin_btn').click()
}
Cypress.Commands.add('login', login);
通過command方式添加接口,此時便可以使用cy.login()使用
設計一個filter
在E2E的測試中我們經(jīng)常遇到的一種場景是我希望只執(zhí)行P0或者 P1的case,這時候改如何設計的,設計一個Filter的函數(shù),代碼如下。
const TestFilter = (definedTags:string[], runTest:Function) => {
if (Cypress.env('TEST_TAGS')) {
const tags = Cypress.env('TEST_TAGS').split(',');
const isFound = definedTags.some((definedTag) => tags.includes(definedTag));
if (isFound) {
runTest();
}
}
};
export default TestFilter;
如何寫case呢?
/// <reference types="Cypress" />
// CYPRESS_TEST_TAGS=P0 yarn cy:test -s "**/testFilter.ts"
// CYPRESS_TEST_TAGS=P1 yarn cy:test -s "**/testFilter.ts" match 0
import TestFilter from '../support/testFilter';
TestFilter(['P0'], () => {
describe('Test A', () => {
it('should run test A successfully', () => {
expect(1 + 1).to.be.equal(2);
});
});
});
當執(zhí)行CYPRESS_TEST_TAGS=P0 yarn cy:test -s "/testFilter.ts" 該case會被執(zhí)行。執(zhí)行CYPRESS_TEST_TAGS=P1 yarn cy:test -s "/testFilter.ts" 此時不會執(zhí)行,因為在case里面的TEST_TAGS為P0,會skip掉這次的測試。