unit
Helpers library for writing tramvai specific unit-tests
It might be even more useful when used with @tramvai/test-mocks
Installation
npm i --save-dev @tramvai/test-unit
How to
Testing reducers
import { testReducer } from '@tramvai/test-unit';
it('test', async () => {
const { dispatch, getState } = testReducer(reducer);
expect(getState()).toEqual([]);
dispatch(event(1));
expect(getState()).toEqual([1]);
});
More examples
import { createEvent, createReducer } from '@tramvai/state';
import { testReducer } from './testReducer';
describe('test/unit/testReducer', () => {
it('should handle state change', () => {
const handle = jest.fn((state: number[], payload: number) => {
return [...state, payload];
});
const event = createEvent<number>('push');
const reducer = createReducer('test', [] as number[]).on(event, handle);
const { dispatch, getState } = testReducer(reducer);
expect(getState()).toEqual([]);
expect(handle).not.toHaveBeenCalled();
dispatch(event(1));
expect(getState()).toEqual([1]);
expect(handle).toHaveBeenCalledWith([], 1);
dispatch(event(3));
expect(getState()).toEqual([1, 3]);
expect(handle).toHaveBeenCalledWith([1], 3);
});
it('should handle several tests reducers at separate', () => {
const event = createEvent<number>('push');
const reducer = createReducer('test', [] as number[]).on(event, (state, payload) => {
return [...state, payload];
});
const test1 = testReducer(reducer);
const test2 = testReducer(reducer);
expect(test1.getState()).toEqual([]);
expect(test2.getState()).toEqual([]);
test1.dispatch(event(1));
expect(test1.getState()).toEqual([1]);
expect(test2.getState()).toEqual([]);
test2.dispatch(event(2));
expect(test1.getState()).toEqual([1]);
expect(test2.getState()).toEqual([2]);
});
});
Testing actions
Tramvai context and DI will be created automatically, otherwise you can directly pass it as an argument.
import { testAction } from '@tramvai/test-unit';
it('test', async () => {
const { run, context } = testAction(action, { initialState: { a: 1 } });
expect(await run(true)).toBe('hello');
expect(await run(false)).toBe('world');
context.getState(); // { a: 1 }
});
More examples
import { createAction, declareAction } from '@tramvai/core';
import { createEvent } from '@tramvai/state';
import { createMockStore } from '@tramvai/test-mocks';
import { testAction } from './testAction';
describe('test/unit/state/testAction', () => {
it('should call action', async () => {
const action = createAction({
name: 'test',
fn: (context, payload: boolean) => {
if (payload) {
return 'hello';
}
return 'world';
},
});
const { run } = testAction(action);
expect(await run(true)).toBe('hello');
expect(await run(false)).toBe('world');
});
it('should call action with custom context', async () => {
const store = createMockStore();
const event = createEvent<string>('test');
const action = declareAction({
name: 'dispatch',
fn(payload: string) {
return this.dispatch(event(`action${payload}`));
},
});
const spyDispatch = jest.spyOn(store, 'dispatch');
const { run } = testAction(action, { store });
await run('ping');
expect(spyDispatch).toHaveBeenCalledWith({ payload: 'actionping', type: 'test' });
await run('pong');
expect(spyDispatch).toHaveBeenCalledWith({ payload: 'actionpong', type: 'test' });
});
it('should not require payload', async () => {
const action = declareAction({
name: 'no-payload',
fn() {
return 'empty';
},
});
const { run } = testAction(action);
await expect(run()).resolves.toBe('empty');
});
});
Testing tramvai module
Testing module in isolation
import { testModule } from '@tramvai/test-unit';
it('test', async () => {
const { di, module, runLine } = testModule(TestModule);
expect(module).toBeInstanceOf(TestModule);
expect(di.get('testToken')).toEqual({ a: 1 });
// Run only specific command line in order to execute handlers for this line inside module
await runLine(commandLineListTokens.generatePage);
});
Testing module in conjunction with other modules
import { createTestApp } from '@tramvai/test-unit';
it('test', async () => {
const { app } = await createTestApp({ modules: [TestModule, DependentModule] });
// get tokens from di implemented by module
expect(app.di.get('testToken')).toEqual({ a: 1 });
});
More examples
import { commandLineListTokens, DI_TOKEN, Module } from '@tramvai/core';
import { Container } from '@tinkoff/dippy';
import { testModule } from './testModule';
describe('test/unit/module/testModule`', () => {
it('should test module', () => {
const mockConstructor = jest.fn();
@Module({
providers: [
{
provide: 'testToken',
useFactory: () => {
return { a: 1 };
},
},
],
deps: {
di: DI_TOKEN,
optToken: { token: 'optional_token', optional: true },
},
})
class TestModule {
constructor(deps: any) {
mockConstructor(deps);
}
}
const { di, module } = testModule(TestModule);
expect(module).toBeInstanceOf(TestModule);
expect(mockConstructor).toHaveBeenCalledWith({ di: expect.any(Container), optToken: null });
expect(di.get('testToken')).toEqual({ a: 1 });
});
it('should test command line', async () => {
const mock = jest.fn();
@Module({
providers: [
{
provide: commandLineListTokens.generatePage,
multi: true,
useFactory: () => {
return mock;
},
},
],
})
class TestModule {}
const { runLine } = testModule(TestModule);
expect(() => runLine(commandLineListTokens.customerStart)).toThrow();
expect(mock).not.toHaveBeenCalled();
await runLine(commandLineListTokens.generatePage);
expect(mock).toHaveBeenCalledWith();
});
});
Adding providers to DI
Most of the helpers accepts option providers
which allows to redefine already existing providers or add new.
For example, passing providers
to helper testAction
allows to access this provider inside action itself:
import { declareAction } from '@tramvai/core';
import { testAction } from '@tramvai/test-unit';
const action = declareAction({
name: 'action',
fn() {
console.log(this.deps.test); // token value
},
deps: {
test: 'token name',
},
});
it('test', async () => {
const { run } = testAction(action, {
providers: [
{
provide: 'token name',
useValue: 'token value',
},
],
});
});
Create app only for testing
import { createTestApp } from '@tramvai/test-unit';
it('test', async () => {
const { app } = await createTestApp({ modules: [TestModule, DependentModule] });
// get tokens from di implemented by module
expect(app.di.get('testToken')).toEqual({ a: 1 });
});
More examples
import http from 'http';
import { ENV_MANAGER_TOKEN } from '@tramvai/tokens-common';
import { SERVER_TOKEN } from '@tramvai/tokens-server';
import { CommonModule } from '@tramvai/module-common';
import detectPort from 'detect-port';
import { createTestApp } from './createTestApp';
describe('test/unit/app/createTestApp', () => {
beforeEach(async () => {
process.env.PORT = (await detectPort(0)).toString();
process.env.PORT_STATIC = (await detectPort(0)).toString();
});
it('should return app', async () => {
const { app, close } = await createTestApp();
const envManager = app.di.get(ENV_MANAGER_TOKEN);
expect(envManager.get('FRONT_LOG_API')).toBe('test');
expect(envManager.get('TEST_ENV')).toBeUndefined();
expect(app.di.get(SERVER_TOKEN)).toBeInstanceOf(http.Server);
return close();
});
it('should specify env', async () => {
const { app, close } = await createTestApp({
env: {
TEST_ENV: '1234',
},
});
const envManager = app.di.get(ENV_MANAGER_TOKEN);
expect(envManager.get('FRONT_LOG_API')).toBe('test');
expect(envManager.get('TEST_ENV')).toBe('1234');
return close();
});
it('should ignore default modules', async () => {
const { app } = await createTestApp({
excludeDefaultModules: true,
modules: [CommonModule],
});
expect(() => app.di.get(SERVER_TOKEN)).toThrow('Token not found');
});
it('should return mocker instance', async () => {
const { mocker, close } = await createTestApp();
expect(mocker).toBeDefined();
return close();
});
});