Skip to content

Commit

Permalink
feat(useTemporaryDirectory): Return an object with useful methods
Browse files Browse the repository at this point in the history
BREAKING CHANGE: useTemporaryDirectory() now returns an object instead of a string
  • Loading branch information
vinsonchuong committed Sep 5, 2020
1 parent 90871a1 commit fa4a320
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 5 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,21 @@ yarn add ava-patterns
Create a temporary directory and delete it (and its contents) at the end of the
test.

Returns an object with the following members:

- `path`: The absolute path to the temporary directory.
- `writeFile(filePath, fileContents)`: Write a file with path relative to the
temporary directory. Any leading whitespace in the file contents is stripped.

```js
import test from 'ava'
import * as path from 'path'
import {promises as fs} from 'fs'
import {useTemporaryDirectory} from 'ava-patterns'

test('writing files', async (t) => {
const directory = await useTemporaryDirectory(t)
await fs.writeFile(path.join(directory, 'file.txt'), 'Hello World!')
await directory.write('file.txt', `
Hello World!
`)
t.pass()
})
```
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"type": "module",
"dependencies": {
"fs-extra": "^9.0.1",
"strip-indent": "^3.0.0",
"tempy": "^0.6.0"
},
"devDependencies": {
Expand Down
14 changes: 13 additions & 1 deletion use-temporary-directory/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import * as path from 'path'
import fs from 'fs-extra'
import tempy from 'tempy'
import stripIndent from 'strip-indent'

export default async function (t) {
const directory = tempy.directory()

await fs.ensureDir(directory)
t.teardown(async () => {
await fs.remove(directory)
})
return directory

return {
path: directory,
async writeFile(filePath, fileContents) {
await fs.writeFile(
path.join(directory, filePath),
stripIndent(fileContents.trim()) + '\n'
)
}
}
}
15 changes: 14 additions & 1 deletion use-temporary-directory/index.test.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import test from 'ava'
import * as path from 'path'
import {promises as fs} from 'fs'
import {useTemporaryDirectory} from '../index.js'

test.serial('creating a directory', async (t) => {
const directory = await useTemporaryDirectory(t)

const stats = await fs.stat(directory)
const stats = await fs.stat(directory.path)
t.true(stats.isDirectory())

await directory.writeFile(
'file.txt',
`
Hello World!
`
)

t.is(
await fs.readFile(path.join(directory.path, 'file.txt'), 'utf8'),
'Hello World!\n'
)

global.directory = directory
})

Expand Down

0 comments on commit fa4a320

Please sign in to comment.