安装jest
yarn add --dev jest
将下面的配置部分添加到你的package.json
里面:
{
"scripts": {
"test": "jest"
}
}
创建文件目录的规则
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
创建测试文件(如何改写模块)
const db = require('../db.js')
const fs = require('fs')
jest.mock('fs') // 必须添加,改写的假fs模块
describe('db', () => {
afterEach(() => {
fs.clearMocks()
})
it('can read', async () => {
const data = [{ title: 'hi', done: true }]
fs.setReadFileMock('/xxx', null, JSON.stringify(data))
const list = await db.read('/xxx')
expect(list).toStrictEqual(data) // 严格相等
})
it('can write', async () => {
let fakeFile
fs.setWriteFileMock('/yyy', (path, data, callback) => {
fakeFile = data
callback(null)
})
const list = [{ title: '见欧阳娜娜', done: true }, { title: '见迪丽热巴', done: true }]
await db.write(list, '/yyy')
expect(fakeFile).toBe(JSON.stringify(list) + '\n')
})
})
如何测试写文件
const fs = jest.genMockFromModule('fs'); // 专门用于测试的模块
const _fs = jest.requireActual('fs'); // 导入真实的fs用的方法
Object.assign(fs, _fs)
let readMocks = {}
fs.setReadFileMock = (path, error, data) => {
readMocks[path] = [error, data]
}
fs.readFile = (path, options, callback) => {
if (callback === undefined) {
callback = options
}
if (path in readMocks) {
callback(...readMocks[path])
} else {
_fs.readFile(path, options, callback)
}
}
let writeMocks = {}
fs.setWriteFileMock = (path, fn) => {
writeMocks[path] = fn
}
fs.writeFile = (path, data, options, callback) => {
if (path in writeMocks) {
writeMocks[path](path, data, options, callback)
} else {
_fs.writeFile(path, data, options, callback)
}
}
检查结果
运行命令
yarn test
运行结果
网友评论