jest-sequence
Testing sequence
A class perfoms some sync or async actions may looks for example like this:
class Test {
other() {}
first(num: number) { return num }
second(str: string) { return str }
async main() {
await quant(1)
this.first(1)
this.other()
await quant(1)
this.second('test')
}
}
To be sure that some of methods is called in appropriate order and at appropriate time and with required arguments the test spec may looks like this:
import { sequence, quant, timeout } from 'jest-sequence'
const methodsOfTestToWatch = [
'main', 'first', 'second'
] as jest.FunctionPropertyNames<Test>[]
describe('test sequence', () => {
afterEach(() => {
jest.restoreAllMocks()
})
it('match known sequence', async () => {
const test = new Test()
const sequence = new Sequence()
sequence.spyOn(Test.prototype, methodsOfTestToWatch)
test.main()
sequence.add(test, 'main', [])
expect(sequence).toMatchSequence()
await quant(1)
sequence.add(test, 'first', [1])
expect(sequence).toMatchSequence()
await quant(1)
sequence.add(test, 'second', ['test'])
expect(sequence).toMatchSequence()
})
})
The utility function timeout
is just promisify setTimeout()
.
The utility function quant(x)
is simple wrapper for timeout(x * quantDuration)
.
The variable quantDuration
by default is 200ms and may be modified via
environment variable JEST_SEQUENCE_QUANT
.
As of now only one Sequence
instance may be instantiated per test case or
several instances per test case must not share same methods to spy on.
Methods received()
and expected()
returns internal representation of
received and expected sequnces (received from spy method and added manually)
respectively. This methods is just for reference (or debug) - representation
of sequences is subject to change.
Method clean()
- does empty of received and expected sequences.