ts-mockito#reset TypeScript Examples
The following examples show how to use
ts-mockito#reset.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: roles.guard.spec.ts From nestjs-rest-sample with GNU General Public License v3.0 | 5 votes |
describe('RolesGuard(ts-mockito)', () => {
let guard: RolesGuard;
const reflecter = mock(Reflector);
beforeEach(() => {
guard = new RolesGuard(instance(reflecter));
});
afterEach(() => {
reset();
});
it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
const context = mock<ExecutionContext>();
when(context.getHandler()).thenReturn({} as any);
const contextInstacne = instance(context);
when(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).thenReturn([] as RoleType[]);
const result = await guard.canActivate(contextInstacne);
expect(result).toBeTruthy();
verify(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).once();
});
it('should return true if the `HasRoles` decorator is set', async () => {
const context = mock<ExecutionContext>();
when(context.getHandler()).thenReturn({} as any);
const arguHost = mock<HttpArgumentsHost>();
when(arguHost.getRequest()).thenReturn({
user: { roles: [RoleType.USER] },
} as any);
when(context.switchToHttp()).thenReturn(instance(arguHost));
const contextInstacne = instance(context);
when(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).thenReturn([RoleType.USER] as RoleType[]);
const result = await guard.canActivate(contextInstacne);
console.log(result);
expect(result).toBeTruthy();
verify(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).once();
});
it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
const context = mock<ExecutionContext>();
when(context.getHandler()).thenReturn({} as any);
// logged in as USER
const arguHost = mock<HttpArgumentsHost>();
when(arguHost.getRequest()).thenReturn({
user: { roles: [RoleType.USER] },
} as any);
when(context.switchToHttp()).thenReturn(instance(arguHost));
const contextInstacne = instance(context);
// but requires ADMIN
when(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).thenReturn([RoleType.ADMIN] as RoleType[]);
const result = await guard.canActivate(contextInstacne);
console.log(result);
expect(result).toBeFalsy();
verify(
reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
).once();
});
});
Example #2
Source File: internal.spec.ts From kin-node with MIT License | 5 votes |
test('submitTransaction already submitted', async () => {
const env = newTestEnv();
const subsidizer = PrivateKey.random();
const [client, txClientV4] = [env.client, env.txClientV4];
const [sender, destination] = [PrivateKey.random().publicKey(), PrivateKey.random().publicKey()];
const tx = new SolanaTransaction({
feePayer: subsidizer.publicKey().solanaKey(),
recentBlockhash: new PublicKey(recentBlockhash).toBase58(),
}).add(
Token.createTransferInstruction(
TOKEN_PROGRAM_ID,
sender.solanaKey(),
destination.solanaKey(),
sender.solanaKey(),
[],
100,
)
);
tx.sign(new SolanaAccount(subsidizer.secretKey()));
const sig = tx.signature!;
when(txClientV4.submitTransaction(anything(), anything(), anything()))
.thenCall((req: transactionpbv4.SubmitTransactionRequest, md: grpc.Metadata, callback) => {
const txSig = new commonpbv4.TransactionSignature();
txSig.setValue(sig);
const resp = new transactionpbv4.SubmitTransactionResponse();
resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.ALREADY_SUBMITTED);
resp.setSignature(txSig);
callback(undefined, resp);
});
try {
await client.submitTransaction(tx);
fail();
} catch (error) {
expect(error).toBeInstanceOf(AlreadySubmitted);
}
reset(txClientV4);
let attempt = 0;
when(txClientV4.submitTransaction(anything(), anything(), anything()))
.thenCall((req: transactionpbv4.SubmitTransactionRequest, md: grpc.Metadata, callback) => {
attempt = attempt + 1;
if (attempt == 1) {
const err: grpc.ServiceError = {
name: "",
message: "",
code: grpc.status.INTERNAL,
};
callback(err, new transactionpbv4.SubmitTransactionResponse());
return;
} else {
const txSig = new commonpbv4.TransactionSignature();
txSig.setValue(sig);
const resp = new transactionpbv4.SubmitTransactionResponse();
resp.setResult(transactionpbv4.SubmitTransactionResponse.Result.ALREADY_SUBMITTED);
resp.setSignature(txSig);
callback(undefined, resp);
}
});
const result = await client.submitTransaction(tx);
expect(result.TxId).toStrictEqual(sig);
expect(result.InvoiceErrors).toBeUndefined();
expect(result.Errors).toBeUndefined();
});
Example #3
Source File: feature-toggle.guard.spec.ts From canopy with Apache License 2.0 | 4 votes |
describe('FeatureToggleGuard', () => {
let configServiceMock: LgFeatureToggleService;
let guard: FeatureToggleGuard;
const routerMock = mock(Router);
const enabledConfig = { parent: true };
const disabledConfig = { parent: false };
const enabledConfig2 = { parent: true, child: true };
const disabledConfig2 = { parent: false, child: false };
const routeSnapshot: Partial<ActivatedRouteSnapshot> = {
data: { featureToggle: 'parent' },
children: [
{
data: { featureToggle: 'child' },
} as any,
],
};
const checkGuardConfigs = (
guardType: GuardTypes,
config,
marbleValue: boolean,
onceVerify: boolean = false,
) => {
/* eslint-disable @typescript-eslint/no-unused-expressions, no-unused-expressions */
onceVerify
? when(configServiceMock.toggles$).thenReturn(config)
: when(configServiceMock.toggles$).thenReturn(of(config));
/* eslint-enable */
switch (guardType) {
case GuardTypes.CAN_ACTIVATE:
expect(guard.canActivate(routeSnapshot as ActivatedRouteSnapshot)).toBeObservable(
cold('(a|)', { a: marbleValue }),
);
break;
case GuardTypes.CAN_ACTIVATE_CHILD:
expect(
guard.canActivateChild(routeSnapshot as ActivatedRouteSnapshot),
).toBeObservable(cold('(a|)', { a: marbleValue }));
break;
case GuardTypes.CAN_LOAD:
expect(guard.canLoad(routeSnapshot as Route)).toBeObservable(
cold('(a|)', { a: marbleValue }),
);
break;
}
return verify(
routerMock.navigate(deepEqual([ '/' ]), deepEqual({ queryParamsHandling: 'merge' })),
);
};
beforeEach(() => {
configServiceMock = mock(LgFeatureToggleService);
TestBed.configureTestingModule({
providers: [
FeatureToggleGuard,
{
provide: LgFeatureToggleService,
useFactory: () => instance(configServiceMock),
},
{ provide: Router, useFactory: () => instance(routerMock) },
],
});
guard = TestBed.inject(FeatureToggleGuard);
});
describe('can activate', () => {
it('should be true when the parent is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE, enabledConfig, true).never();
reset(routerMock);
});
it('should be true when the parent and child is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE, enabledConfig2, true).never();
reset(routerMock);
});
it('should be false when the parent is disabled', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, disabledConfig, false).once();
reset(routerMock);
});
it('should be false when the parent is enabled but not child', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE, disabledConfig2, false).once();
reset(routerMock);
});
});
describe('can activate child', () => {
it('should be true when the parent is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, of(enabledConfig), true).never();
reset(routerMock);
});
it('should be true when the parent and child is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_ACTIVATE_CHILD, of(enabledConfig2), true).never();
reset(routerMock);
});
it('should be false when the parent is disabled', () => {
checkGuardConfigs(
GuardTypes.CAN_ACTIVATE_CHILD,
of(disabledConfig),
false,
true,
).once();
reset(routerMock);
});
it('should be false when the parent is enabled but not child', () => {
checkGuardConfigs(
GuardTypes.CAN_ACTIVATE_CHILD,
of(disabledConfig2),
false,
true,
).once();
reset(routerMock);
});
});
describe('can load', () => {
it('should be true when the parent is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_LOAD, of(enabledConfig), true).never();
reset(routerMock);
});
it('should be true when the parent and child is enabled', () => {
checkGuardConfigs(GuardTypes.CAN_LOAD, of(enabledConfig2), true).never();
reset(routerMock);
});
it('should be false when the parent is disabled', () => {
checkGuardConfigs(GuardTypes.CAN_LOAD, of(disabledConfig), false, true).once();
reset(routerMock);
});
it('should be false when the parent is enabled but not child', () => {
checkGuardConfigs(GuardTypes.CAN_LOAD, of(disabledConfig2), false, true).once();
reset(routerMock);
});
});
});
Example #4
Source File: ModelManager.test.ts From aem-spa-page-model-manager with Apache License 2.0 | 4 votes |
describe('ModelManager ->', () => {
const PAGE_MODEL_LOAD_EVENT_OPTIONS = {
detail: {
model: PAGE_MODEL
}
};
function expectPageModelLoadedEventFired() {
expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalled();
expect(PathUtils.dispatchGlobalCustomEvent).toHaveBeenCalledWith(EventType.PAGE_MODEL_LOADED, PAGE_MODEL_LOAD_EVENT_OPTIONS);
}
function assertAsyncModelFetched() {
expectPageModelLoadedEventFired();
return ModelManager.getData().then((data) => {
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
}
function mockTheFetch(path: any, data: any) {
REQUEST_MAP[path] = data;
}
let pathName = '';
let metaProps: { [key: string]: string } = {};
const isRouteExcludedSpy = isRouteExcluded as jest.MockedFunction<(route: string) => boolean>;
beforeEach(() => {
metaProps = {};
metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
pathName = PAGE_PATH;
when(ModelClientMock.fetch(anyString())).thenReturn(Promise.resolve(PAGE_MODEL));
when(ModelClientMock.fetch(PAGE_MODEL_URL)).thenReturn(Promise.resolve(PAGE_MODEL));
when(ModelClientMock.fetch(CHILD_MODEL_URL)).thenReturn(Promise.resolve(content_test_page_root_child0000_child0010));
when(ModelClientMock.fetch(NON_EXISTING_MODEL_URL))
.thenReturn(Promise.reject({ response: { status: 404, statusText: 'Could not find page' } }));
when(ModelClientMock.fetch(ERROR_MODEL_URL)).thenReturn(Promise.reject('Some Error without json'));
when(ModelClientMock.fetch(ERROR_MODEL_URL_404)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_404));
when(ModelClientMock.fetch(ERROR_MODEL_URL_500)).thenReturn(Promise.resolve(ERROR_PAGE_MODEL_500));
modelClient = instance(ModelClientMock);
jest.spyOn(PathUtils, 'getMetaPropertyValue').mockImplementation((val) => metaProps[val]);
jest.spyOn(PathUtils, 'dispatchGlobalCustomEvent');
jest.spyOn(PathUtils, 'getCurrentPathname').mockImplementation(() => pathName);
isRouteExcludedSpy.mockImplementation(() => false);
mockTheFetch(PAGE_MODEL_URL, PAGE_MODEL);
});
afterEach(() => {
reset(ModelClientMock);
pathName = '';
});
describe('initialize ->', () => {
describe('Initialization without config object ->', () => {
it('should NOT fetch remote data on initialization when the model is provided', () => {
return ModelManager.initialize({ model: PAGE_MODEL }).then((data) => {
expectPageModelLoadedEventFired();
expect(data).toEqual(PAGE_MODEL);
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should fetch remote data on initialization - root path as meta property', () => {
metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
return ModelManager.initialize().then((data) => {
expectPageModelLoadedEventFired();
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should fetch remote data on initialization - root path as currentPathname', () => {
pathName = PAGE_MODEL_URL;
return ModelManager.initialize().then((data) => {
expectPageModelLoadedEventFired();
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should fetch remote data on initialization - root path as a parameter', () => {
return ModelManager.initialize(PAGE_PATH).then((data) => {
expectPageModelLoadedEventFired();
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
});
it('should fetch remote data on initialization', () => {
return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
verify(modelClient.fetch(anyString()));
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should fail when initialized on non-browser with invlid config', () => {
pathName = '';
// disable console.error within the test
jest.spyOn(console, 'error').mockImplementation();
//simulate non browser for the test
const windowSpy = jest.spyOn(global, 'window', 'get');
windowSpy.mockImplementation();
try {
ModelManager.initialize();
} catch (err) {
assert.strictEqual(err.name, 'Error');
}
windowSpy.mockRestore();
});
it('should throw error when initialized without model url', () => {
metaProps = {};
pathName = '';
try {
ModelManager.initialize();
} catch (err) {
assert.strictEqual(err.name, 'Error');
}
});
it('should throw error when initialized with invalid model url', () => {
try {
ModelManager.initialize({ path: '?abc' });
} catch (err) {
assert.strictEqual(err.name, 'Error');
}
});
it('should not make concurrent server calls on duplicate request', () => {
return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
expectPageModelLoadedEventFired();
pathName = '/content/test/duplicate/request';
when(ModelClientMock.fetch(pathName)).thenReturn(new Promise((resolve) => {
setTimeout(() => resolve(PAGE_MODEL), 200);
}));
const promises: any[] = [];
promises.push(ModelManager._fetchData(pathName));
promises.push(ModelManager._fetchData(pathName));
promises.push(ModelManager._fetchData(pathName));
return Promise.all(promises).then(() => {
for (let i = 0; i < promises.length - 1; ++i) {
expect(promises[i]).toEqual(promises[i + 1]);
}
});
});
});
describe('when the request is for an asynchronous subpage -- ', () => {
beforeEach(() => {
pathName = '/content/test/pageNotInModel';
metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = '/content/test';
});
it('should fetch data twice on initialization', () => {
return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
expectPageModelLoadedEventFired();
verify(ModelClientMock.fetch(anyString())).times(2);
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should fetch data once on initialization when sub page route path is excluded', () => {
isRouteExcludedSpy.mockReturnValue(true);
return ModelManager.initialize({ path: PAGE_PATH, modelClient: modelClient }).then((data) => {
expectPageModelLoadedEventFired();
verify(ModelClientMock.fetch(anyString())).times(1);
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
});
it('should not fetch data on initialization', () => {
return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then((data) => {
expectPageModelLoadedEventFired();
// verify(ModelClientMock.fetch(anyString())).never();
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should not fetch data', () => {
return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
expectPageModelLoadedEventFired();
return ModelManager.getData(CHILD_PATH).then((data) => {
verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
});
});
});
it('should fetch all the data', () => {
return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
expectPageModelLoadedEventFired();
return ModelManager.getData().then((data) => {
verify(ModelClientMock.fetch(CHILD_MODEL_URL)).never();
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
});
it('should fetch data if forced', () => {
return ModelManager.initialize({ path: PAGE_PATH, model: PAGE_MODEL, modelClient: modelClient }).then(() => {
expectPageModelLoadedEventFired();
return ModelManager.getData({ path: CHILD_PATH, forceReload: true }).then((data) => {
verify(ModelClientMock.fetch(anyString())).times(1);
assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
});
});
});
});
describe('initializeAsync ->', () => {
describe('Initialization without config object ->', () => {
it('should fetch remote data on initialization - root path as meta property', () => {
metaProps[MetaProperty.PAGE_MODEL_ROOT_URL] = PAGE_MODEL_URL;
ModelManager.initializeAsync();
assertAsyncModelFetched();
});
it('should fetch remote data on initialization - root path as currentPathname', () => {
pathName = PAGE_MODEL_URL;
ModelManager.initializeAsync();
assertAsyncModelFetched();
});
it('should initialize model store when no root path is provided', () => {
metaProps = {};
pathName = '';
ModelManager.initializeAsync();
return ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
});
it('should fetch standalone item data', () => {
metaProps = {};
pathName = '';
ModelManager.initializeAsync();
return ModelManager.getData({ path: CHILD_PATH }).then((data) => {
assert.deepEqual(data, content_test_page_root_child0000_child0010, 'data should be correct');
});
});
it('should throw error when fetching data without initialization', () => {
ModelManager.getData({ path: PAGE_MODEL_URL }).then((data) => {
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
});
});
it('should NOT fetch remote data on initialization when the model is provided', () => {
ModelManager.initializeAsync({ model: PAGE_MODEL });
assertAsyncModelFetched();
});
it('should fetch remote data on initialization - root path as a parameter', () => {
ModelManager.initializeAsync(PAGE_PATH);
assertAsyncModelFetched();
});
it('should fetch remote data on initialization', () => {
ModelManager.initializeAsync({ path: PAGE_PATH, modelClient: modelClient });
verify(modelClient.fetch(anyString()));
assertAsyncModelFetched();
});
it('should load a 404 error page.', async () => {
const configuration:ModelManagerConfiguration = {
path: PAGE_PATH,
modelClient: modelClient,
errorPageRoot: ERROR_PAGE_ROOT
};
const data:Model = await ModelManager.initialize(configuration);
verify(modelClient.fetch(anyString()));
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
const nonExistingData = await ModelManager._fetchData(NON_EXISTING_PATH);
assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_404, 'data should be correct');
});
it('should load a 500 error page.', async () => {
const configuration:ModelManagerConfiguration = {
path: PAGE_PATH,
modelClient: modelClient,
errorPageRoot: ERROR_PAGE_ROOT
};
const data:Model = await ModelManager.initialize(configuration);
verify(modelClient.fetch(anyString()));
assert.deepEqual(data, PAGE_MODEL, 'data should be correct');
const nonExistingData = await ModelManager._fetchData(PAGE_WITH_ERROR_PATH);
assert.deepEqual(nonExistingData, ERROR_PAGE_MODEL_500, 'data should be correct');
});
});
});