0.3.2 • Published 4 years ago
fixture-injection v0.3.2
fixture-injection
Note: fixture-injection is still in alpha stage.
fixture-injection is a test helper tool for Jest and Jasmine to define and use fixtures easily by leveraging dependency injection.
Fixtures are code that sets up test subjects and the testing environment
defined as a value or a function. These fixtures can be injected to
beforeAll()
, it()
, test()
, etc. as arguments.
Usage
tests/__fixtures__.js
:
// Example 1) Simple value
const foo = 'FOO'
// Example 2) Fixture function to provide a value which requires another fixture `foo`
const bar = (foo) => `BAR(${foo})`
// Example 3) Asynchronous fixture function to provide a value
const baz = async (provide, bar) => { // requires another fixture `bar`
// Write setup code here
await provide(`BAZ(${bar}`) // provide the value
// `await` above waits until the context (test case or suite) finishes
// Write teardown code here
}
module.exports = {
foo,
bar,
baz
}
example.spec.js
:
describe('My test suite', () => {
let fixtures = {}
beforeAll((foo) => { // Inject fixtures to *a suite* by beforeAll()
fixtures.foo = foo
})
test('with fixtures', (bar, baz) => { // Inject fixtures to *a test case*
// bar and baz are initialized just before this block
const { foo } = fixtures // Get fixtures from the suite
expect(foo).toEqual('FOO')
expect(bar).toEqual('BAR(FOO)')
expect(baz).toEqual('BAZ(BAR(FOO))')
// bar and baz are released just after this block
})
// foo is released by hidden afterAll() of this block automatically
})
Features
- The code in the fixture function can do whatever you want
- Fixture function can be asynchronous and can have setup and teardown
code around
await provide()
- Fixtures are also available in other fixtures, and the dependencies are
automatically resolved
- Asynchronous fixtures are initialized concurrently as much as possible
- Local fixtures are initialized every time in each injected context
- Global fixtures are singletons and initialized only once
- Jest They are initialized by Jest runner and will be sent to individual test workers via IPC
- In-line fixtures are also available by
fixture()
in each test file
Packages
- fixture-injection
- Core package of fixture-injection
- jest-fixture-injection
- Jest extension to use fixture-injection
- jasmine-fixture-injection
- Jasmine extension to use fixture-injection
Install/Setup
See the documentation of each test framework extension.