概述
我有一个用nodejs编写的简单模块,它使用fs-extra包测试文件是否存在。当路径存在时,模块抛出,否则继续下一个过程。以下是源文件:
// - main.js -
import fs from 'fs-extra'
export default async (pathName) => {
// Do not proceed if path already exists.
if (await fs.pathExists(projectPath)) {
throw new Error(chalk.red.bold(`${projectPath} already exists`))
}
// more logic here
}我想编写一个单元测试,测试下面的逻辑:
我不想搞砸真正的文件系统-in --我的代码包含了一些可能摧毁它的讨厌的bug --所以我选择了另一种解决方案,使用mock-fs来嘲弄文件系统。下面是规范文件:
// - main.js spec file -
import mainFunction from '../main'
import mockfs from 'mock-fs'
describe('test main function', () => {
beforeEach(() => {
mockfs({
home: {
user: {
dummy: {}
}
}
})
})
test('expect to throw', async () => {
await mainFunction('/home/user/dummy')
})
afterEach(() => {
mockfs.restore()
})
})有什么问题吗?
每次我运行测试时,主函数都不会抛出。这是因为mockfs伪造文件系统是在规范文件中声明的,所以主源文件中的fs模块不知道mockfs伪造文件系统并检查真实的文件系统。当我在实际的文件系统中没有名为/home/user/dummy的文件夹时,检查总是失败的。
预期行为
规范文件中的mainFunction应该抛出
实际行为
规范文件中的mainFunction不引发
其他信息
我想我可以把这个单元测试变成一个集成测试。但我不想。有什么解决办法吗?我要用别的包裹吗?我的测试服是Jest 22.3.0。
发布于 2018-02-27 12:44:37
经过一些搜索,我找到了适当的方法来测试分支。我们实际上不必使用mock-fs模块。我们只需模拟fs-extra模块的fs-extra方法就可以返回一次值false和一次值true。贝娄,我发布了我的规范文件的工作版本:
import mainFunction from '../main'
require('fs-extra').pathExists = jest.fn().mockReturnValueOnce(false).mockReturnValueOnce(true)
describe('test main function', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('expect to not throw', async () => {
await expect(mainFunction('/dummy/path/does/not/matter')).resolves
})
test('expect to throw', async () => {
await expect(mainFunction('/dummy/path/does/not/matter')).rejects.toBeInstanceOf(Error)
})
})https://stackoverflow.com/questions/49008358
复制相似问题