angular - 如果您使用的是材料形式,请在 Angular 中使用 cypress 进行选择
问题描述
我有一个看起来像这样的表格:
<form class="col s12" materialize [formGroup]="newUserForm">
...
<div class="row">
<div class="input-field col m4 s12">
<select formControlName="genderBound" materialize="material_select" id="gender" name="test">
<option value="" disabled selected name="chooseGender">Choose gender</option>
<option *ngFor="let gender of genders">{{gender}}</option>
</select>
<label for="gender">Gender</label>
</div>
...
当我尝试使用 cypress 选择下拉菜单时,它告诉我它不可见。当我按照 cypress 提供的解释性 URL 进行操作时,它建议我{force: true}
在点击中使用。这让我的测试通过了,但实际上似乎从未选择过这些项目。
我也按照这里提供的解决方案,并在实际选项上实现了一个 jQuery 点击(注意我的 select 和 option 标签不是 md-select 和 md-option 标签)
sample.spec.js 在我的 cypress 目录中:
...
it('signs up a new user', () =>{
cy.get('button[id=new-account-button]').click();
cy.get('input[id=affiliation]').type(affiliation);
cy.get('input[id=password]').type(pass);
cy.get('input[id=userName]').type(name);
cy.get('input[id=email]').type(email);
//Now the options
cy.get('[name="chooseGender"]').click({force: true});
cy.get('option').contains("Female").then(option =>{
cy.wrap(option).contains("Female");
option[0].click();
});
...
我想有两点我不太明白:
- 为什么没有实际选择一个选项?
- 尽管如此,为什么测试通过了?
我在下面提供了一个包含我的确切问题的回购:
git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout cypress-SO
在 /src/app 中创建一个 api-keys.ts 文件并用要遵循的文本填充它
npm install
ng serve
(在单独的终端选项卡中)
npm run e2e
api-keys.ts:
export var masterFirebaseConfig = {
apiKey: "AIzaSyCaYbzcG2lcWg9InMZdb10pL_3d1LBqE1A",
authDomain: "dataJitsu.firebaseapp.com",
databaseURL: "https://datajitsu.firebaseio.com",
storageBucket: "",
messagingSenderId: "495992924984"
};
export var masterStripeConfig = {
publicApiTestKey: "pk_test_NKyjLSwnMosdX0mIgQaRRHbS",
secretApiTestKey: "sk_test_6YWZDNhzfMq3UWZwdvcaOwSa",
publicApiKey: "",
secretApiKey: ""
};
解决方案
对于 Angular 7+ 中的 mat-select,您必须使用 Promise 来等待模态 cdk-overlay 中的选项可用。
这是一个用于重用的辅助函数:
function selectMaterialDropDown(formControlName, selectOption) {
cy.get(`[formcontrolname="${formControlName}"]`).click().then(() => {
cy.get(`.cdk-overlay-container .mat-select-panel .mat-option-text`).should('contain', selectOption);
cy.get(`.cdk-overlay-container .mat-select-panel .mat-option-text:contains("${selectOption}")`).first().click().then(() => {
// After click, mat-select should contain the text of the selected option
cy.get(`[formcontrolname="${formControlName}"]`).contains(selectOption);
});
});
}
调用函数:
selectMaterialDropDown('myMatSelectControlName', 'OptionTextToSelect');
推荐阅读
- cookies - nextjs cookie 未添加到 axios 请求客户端
- c# - Roslyn 分析器/代码修复依赖项
- typescript - 在量角器中找不到带有黄瓜和打字稿的规范
- c# - 我的查询有什么问题?为什么每次单击列按钮时都会出错?
- java - 使用Java14手动编译模块,但报错
- c - 制作没有外部依赖的网络摄像头快照
- laravel - PhpStorm Laravel Homestead “错误:测试类未指定或无效”
- firefox - 打印 firefox session id 和 command executor url:这是什么意思?
- javascript - onAuthStateChange 中的 setState 不起作用
- reactjs - 反应部署问题