在Debian上进行Node.js自动化测试,可按以下步骤操作:
安装Node.js和npm
sudo apt update
sudo apt install nodejs npm
验证安装:node -v、npm -v。
选择并安装测试框架
npm install --save-dev jest
npm install --save-dev mocha chai
npm install --save-dev cypress
编写测试用例
__tests__目录创建sum.test.js:const sum = require('../sum');
test('1+2=3', () => {
expect(sum(1, 2)).toBe(3);
});
const { expect } = require('chai');
describe('Array', () => {
it('should return -1 for non-existent value', () => {
expect([1,2,3].indexOf(4)).to.equal(-1);
});
});
运行测试
npx jest
package.json脚本:"scripts": { "test": "jest" }
然后运行:npm test。集成到CI/CD
.github/workflows/node.js.yml中配置:name: Node.js CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with: { node-version: '16.x' }
- run: npm ci
- run: npm test
可选:添加测试报告
jest-junit生成JUnit格式报告:npm install --save-dev jest-junit
在jest.config.js中配置:module.exports = {
reporters: ['default', 'jest-junit'],
reporters: [{
reporter: 'jest-junit',
outputDirectory: 'reports',
outputName: 'junit.xml'
}]
};
工具选择参考:
以上步骤参考自。