在 Cypress 中的测试都是在前端运行的, 一些后端的操作是不可以直接调用的, 例如 fs, 但是可以通过 task 作为桥梁进行调用.
1. 在 cypress.config.js 中配置
e2e: {setupNodeEvents(on, config) {plugins(on, config);},
2. 在 plugins/index.js 中实现
const fs = require("fs");
const Sms = require("../support/dkd/common/sms");module.exports = (on, config) => {on("task", {readFileSync({ src }) {return fs.readFileSync(src);},smsCode({ config, nationCode, phoneNo }) {return new Sms(config).getCode(nationCode, phoneNo);},});
};
3. 在测试中使用
3.1 普通的返回
- 如果返回的是个字符串直接就可以通过
cy.task()的返回值获取了. - 如果返回的是个
Buffer, 则需要使用await cy.task()并且获取返回值后转换成Buffer(`Buffer.from(xxx) - `)
例如:
const xxx = await cy.task("readFileSync", { src: __dirname + "/xxxxxx/xxx.xx" });
Buffer.from(xxx)
3.2 如果返回的是一个 promise
必须使用 .then, 使用 await 没有用.
例如:
cy.task("smsCode", { config, nationCode: "+86", phoneNo }).then((smsCode) => {cy.get('#xxxx').should("be.visible").type(smsCode);});
看起来很奇怪, 通常在 js 中以下两种是可以通用的:
const xxx = await fff()fff().then((xxx) => {})
但是在这里不行, 一定要使用 then() 否则在最开始就直接执行了 await cy.task() 后面的语句, 不会等待其返回.