测试环境变量
mysql.ts
const MySQLConf = {
development: {
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'local_db',
},
production: {
host: 'www.jianshu.com',
port: 3306,
user: 'root',
password: 'root',
database: 'online_db',
},
};
export default MySQLConf[process.env.NODE_ENV ?? 'development'];
mysql.spec.ts
describe('环境变量', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
delete process.env.NODE_ENV;
});
it('development', () => {
process.env.NODE_ENV = 'development';
const MySQLConf = require('./mysql').default;
const expected = {
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'local_db',
};
expect(MySQLConf).toEqual(expected);
});
it('production', () => {
process.env.NODE_ENV = 'production';
const MySQLConf = require('./mysql').default;
const expected = {
host: 'www.jianshu.com',
port: 3306,
user: 'root',
password: 'root',
database: 'online_db',
};
expect(MySQLConf).toEqual(expected);
});
});
说明
每次执行一个
it
方法后执行(注:用 afterEach 方法也行,只是一个前后的问题)
多个测试有共享状态时,每次测试完成之后需要用 jest.resetModules() 重置模块 ,它会清空所有 required 模块的缓存,保证模块之间的隔离
网友评论