Skip to content

Commit

Permalink
feat!: mocking timers with sinon (#531)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Jan 23, 2022
1 parent 75113c7 commit cf30e5a
Show file tree
Hide file tree
Showing 11 changed files with 1,109 additions and 511 deletions.
33 changes: 27 additions & 6 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,10 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
.advanceTimersToNextTimer() // log 3
```

### vi.clearAllTimers

Removes all timers that are scheduled to run. These timers will never run in the future.

### vi.fn

- **Type:** `(fn: Function) => CallableMockInstance`
Expand All @@ -1074,11 +1078,17 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
expect(getApples).toHaveReturnedNthTimeWith(1, 5)
```

### vi.getMockedDate
### vi.getMockedSystemTime

- **Type**: `() => Date | null`

- **Type**: `() => string | number | Date`
Returns mocked current date that was set using `setSystemTime`. If date is not mocked, will return `null`.

Returns mocked current date that was set using `mockCurrentDate`. If date is not mocked, will return `null`.
### vi.getRealSystemTime

- **Type**: `() => number`

When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.

### vi.mock

Expand All @@ -1092,7 +1102,7 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo

Additionally, unlike Jest, mocked modules in `<root>/__mocks__` are not loaded unless `vi.mock()` is called. If you need them to be mocked in every test, like in Jest, you can mock them inside [`setupFiles`](/config/#setupfiles).

### vi.mockCurrentDate
### vi.setSystemTime

- **Type**: `(date: string | number | Date) => void`

Expand All @@ -1103,9 +1113,12 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
```ts
const date = new Date(1998, 11, 19)

vi.mockCurrentDate(date)
vi.useFakeTimers()
vi.setSystemTime(date)

expect(Date.now()).toBe(date.valueOf())

vi.useRealTimers()
```

### vi.mocked
Expand Down Expand Up @@ -1153,6 +1166,12 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo

Restores `Date` back to its native implementation.

### vi.runAllTicks

- **Type:** `() => Vitest`

Calls every microtask. These are usually queued by `proccess.nextTick`. This will also run all microtasks scheduled by themselves.

### vi.runAllTimers

- **Type:** `() => Vitest`
Expand Down Expand Up @@ -1216,7 +1235,9 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo

- **Type:** `() => Vitest`

To enable mocking timers, you need to call this method. It will wrap all further calls to timers, until [`vi.useRealTimers()`](#userealtimers) is called.
To enable mocking timers, you need to call this method. It will wrap all further calls to timers (such as `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `nextTick`, `setImmediate`, `clearImmediate`, and `Date`), until [`vi.useRealTimers()`](#userealtimers) is called.

The implementation is based internally on [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).

### vi.useRealTimers

Expand Down
4 changes: 1 addition & 3 deletions docs/guide/debugging.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@

To debug a test file in VSCode, create the following launch configuration.

```
```json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
Expand Down
13 changes: 9 additions & 4 deletions docs/guide/mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ If you wanna dive in head first, check out the [API section](/api/#vi) otherwise

## Dates

Sometimes you need to be in control of the date to ensure consistency when testing. Vitest comes with the [`mockdate`](https://www.npmjs.com/package/mockdate) package built-in to let you manipulate the system date in your tests. You can find more about the specific API in detail [here](/api/#vi-mockcurrentdate).
Sometimes you need to be in control of the date to ensure consistency when testing. Vitest uses [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers) package for manipulating timers, as well as system date. You can find more about the specific API in detail [here](/api/#vi-setsystemtime).

### Example

Expand All @@ -30,15 +30,20 @@ const purchase = () => {
};

describe('purchasing flow', () => {
beforeEach(() => {
// tell vitest we use mocked time
vi.useFakeTimers()
});

afterEach(() => {
// restoring date after each test run
vi.restoreCurrentDate()
vi.useRealTimers()
});

it('allows purchases within business hours', () => {
// set hour within business hours
const date = new Date(2000, 1, 1, 13)
vi.mockCurrentDate(date)
vi.setSystemTime(date)

// access Date.now() will result in the date set above
expect(purchase()).toEqual({ message: 'Success' })
Expand All @@ -47,7 +52,7 @@ describe('purchasing flow', () => {
it('disallows purchases outside of business hours', () => {
// set hour outside business hours
const date = new Date(2000, 1, 1, 19)
vi.mockCurrentDate(date)
vi.setSystemTime(date)

// access Date.now() will result in the date set above
expect(purchase()).toEqual({ message: 'Error' })
Expand Down
111 changes: 82 additions & 29 deletions packages/vitest/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,61 @@ Repository: https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk
---------------------------------------

## @sinonjs/commons
License: BSD-3-Clause
Repository: git+https://github.com/sinonjs/commons.git

> BSD 3-Clause License
>
> Copyright (c) 2018, Sinon.JS
> All rights reserved.
>
> Redistribution and use in source and binary forms, with or without
> modification, are permitted provided that the following conditions are met:
>
> * Redistributions of source code must retain the above copyright notice, this
> list of conditions and the following disclaimer.
>
> * Redistributions in binary form must reproduce the above copyright notice,
> this list of conditions and the following disclaimer in the documentation
> and/or other materials provided with the distribution.
>
> * Neither the name of the copyright holder nor the names of its
> contributors may be used to endorse or promote products derived from
> this software without specific prior written permission.
>
> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------

## @sinonjs/fake-timers
License: BSD-3-Clause
By: Christian Johansen
Repository: https://github.com/sinonjs/fake-timers.git

> Copyright (c) 2010-2014, Christian Johansen, [email protected]. All rights reserved.
>
> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
>
> 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
>
> 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
>
> 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
>
> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------

## ansi-escapes
License: MIT
By: Sindre Sorhus
Expand Down Expand Up @@ -1176,35 +1231,6 @@ Repository: unjs/mlly
---------------------------------------

## mockdate
License: MIT
By: Bob Lauer
Repository: https://github.com/boblauer/MockDate.git

> The MIT License (MIT)
>
> Copyright (c) 2014 Bob Lauer
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all
> copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
---------------------------------------

## natural-compare
License: MIT
By: Lauri Rooden
Expand Down Expand Up @@ -1853,6 +1879,33 @@ Repository: micromatch/to-regex-range
---------------------------------------

## type-detect
License: MIT
By: Jake Luer, Keith Cirkel, David Losert, Aleksey Shvayka, Lucas Fernandes da Costa, Grant Snodgrass, Jeremy Tice, Edward Betts, dvlsg, Amila Welihinda, Jake Champion, Miroslav Bajtoš
Repository: git+ssh:https://[email protected]/chaijs/type-detect.git

> Copyright (c) 2013 Jake Luer <[email protected]> (http:https://alogicalparadox.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------

## vite-node
License: MIT
By: Anthony Fu
Expand Down
5 changes: 3 additions & 2 deletions packages/vitest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,14 @@
},
"devDependencies": {
"@antfu/install-pkg": "^0.1.0",
"@sinonjs/fake-timers": "^8.0.1",
"@types/diff": "^5.0.2",
"@types/jsdom": "^16.2.14",
"@types/micromatch": "^4.0.2",
"@types/natural-compare": "^1.4.1",
"@types/node": "^17.0.10",
"@types/prompts": "^2.4.0",
"@types/sinonjs__fake-timers": "^8.1.1",
"@vitest/ui": "workspace:*",
"birpc": "^0.1.0",
"c8": "^7.11.0",
Expand All @@ -88,7 +90,6 @@
"magic-string": "^0.25.7",
"micromatch": "^4.0.4",
"mlly": "^0.3.19",
"mockdate": "^3.0.5",
"natural-compare": "^1.4.0",
"pathe": "^0.2.0",
"picocolors": "^1.0.0",
Expand Down Expand Up @@ -125,4 +126,4 @@
"engines": {
"node": ">=14.14.0"
}
}
}
Loading

0 comments on commit cf30e5a

Please sign in to comment.