ts-mockito#anyString TypeScript Examples
The following examples show how to use
ts-mockito#anyString.
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: userStorage.spec.ts From space-sdk with MIT License | 4 votes |
initStubbedStorage = (): { storage: UserStorage; mockBuckets: Buckets } => {
const mockBuckets: Buckets = mock();
when(mockBuckets.getOrCreate(anyString(), anything())).thenReturn(
Promise.resolve({
root: {
...mock<Root>(),
key: 'myBucketKey',
},
}),
);
// const mockMetadataStore: UserMetadataStore = mock();
// when(mockMetadataStore.findBucket(anyString())).thenReturn(Promise.resolve(undefined));
// when(mockMetadataStore.createBucket(anyString(), anyString())).thenReturn(Promise.resolve({
// slug: 'myBucketKey',
// encryptionKey: new Uint8Array(80),
// dbId: 'dbId',
// }));
const storage = new UserStorage(
{
identity: mockIdentity,
token: '',
endpoint: 'http://space-auth-endpoint.com',
storageAuth: {
key: 'random-key',
token: 'token',
sig: 'sig',
msg: 'msg',
},
},
{
bucketsInit: () => instance(mockBuckets),
metadataStoreInit: async (): Promise<UserMetadataStore> =>
// commenting this out now because it causes test to silently fail
// return instance(mockMetadataStore); // to be fixed later
// eslint-disable-next-line implicit-arrow-linebreak
Promise.resolve({
createBucket(bucketSlug: string, dbId: string): Promise<BucketMetadata> {
return Promise.resolve({
bucketKey: 'testkey',
slug: 'myBucketKey',
encryptionKey: new Uint8Array(80),
dbId: 'dbId',
});
},
findBucket(bucketSlug: string): Promise<BucketMetadata | undefined> {
return Promise.resolve({
bucketKey: 'testkey',
slug: 'myBucketKey',
encryptionKey: new Uint8Array(80),
dbId: 'dbId',
});
},
listBuckets(): Promise<BucketMetadata[]> {
return Promise.resolve([]);
},
upsertFileMetadata(input: FileMetadata): Promise<FileMetadata> {
return Promise.resolve({ ...input, bucketSlug: 'myBucket', dbId: '', path: '/' });
},
findFileMetadata(bucketSlug, dbId, path): Promise<FileMetadata | undefined> {
return Promise.resolve({
uuid: 'generated-uuid',
mimeType: 'generic/type',
encryptionKey,
bucketSlug,
dbId,
path,
});
},
findFileMetadataByUuid(): Promise<FileMetadata | undefined> {
return Promise.resolve({
mimeType: 'generic/type',
bucketSlug: 'myBucket',
bucketKey: 'myBucketKey',
dbId: 'mockThreadId',
path: '/',
encryptionKey,
});
},
setFilePublic(_metadata: FileMetadata): Promise<void> {
return Promise.resolve();
},
async upsertSharedWithMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
return data;
},
async listSharedWithMeFiles(): Promise<SharedFileMetadata[]> {
return [];
},
async upsertSharedByMeFile(data: SharedFileMetadata): Promise<SharedFileMetadata> {
return data;
},
async findSharedFilesByInvitation(id: string): Promise<SharedFileMetadata | undefined> {
return undefined;
},
async listSharedByMeFiles(): Promise<SharedFileMetadata[]> {
return [];
},
async addUserRecentlySharedWith(data: ShareUserMetadata): Promise<ShareUserMetadata> {
return data;
},
async listUsersRecentlySharedWith(): Promise<ShareUserMetadata[]> {
return [];
},
async getNotificationsLastSeenAt():Promise<number> {
return Date.now();
},
async setNotificationsLastSeenAt(timestamp:number):Promise<void> {
noop;
},
}),
},
);
return { storage, mockBuckets };
}
Example #2
Source File: userStorage.spec.ts From space-sdk with MIT License | 4 votes |
describe('UserStorage', () => {
describe('createFolder()', () => {
it('should throw error if user is not authenticated', async () => {
const storage = new UserStorage({ identity: mockIdentity, token: '', endpoint: '' });
await expect(storage.createFolder({ bucket: '', path: '' })).to.eventually.be.rejectedWith(UnauthenticatedError);
});
it('should push empty .keep file to bucket at specified path', async () => {
const createFolderRequest = { bucket: 'personal', path: 'topLevel' };
const { storage, mockBuckets } = initStubbedStorage();
await storage.createFolder(createFolderRequest);
verify(
mockBuckets.pushPath(
'myBucketKey',
'.keep',
deepEqual({
path: '/topLevel/.keep',
content: Buffer.from(''),
}),
),
).called();
});
});
describe('listDirectory()', () => {
it('should throw error if user is not authenticated', async () => {
const storage = new UserStorage({ identity: mockIdentity, token: '', endpoint: '' });
await expect(storage.listDirectory({ bucket: 'bucket', path: '' })).to.eventually.be.rejectedWith(
UnauthenticatedError,
);
});
it('should return list of items', async () => {
const listDirectoryRequest = { bucket: 'personal', path: 'topLevel' };
const mainItem = mock<PathItem>();
const childItem = {
name: 'folder',
path: '/ipfs/Qm123/folder',
cid: 'Qm...',
isDir: true,
size: 10,
};
const updatedAt = (new Date().getMilliseconds()) * 1000000;
const { storage, mockBuckets } = initStubbedStorage();
when(mockBuckets.listPath('myBucketKey', `/${listDirectoryRequest.path}`, 0)).thenResolve({
item: {
...mainItem,
items: [
{
...childItem,
metadata: {
updatedAt,
roles: new Map(),
},
items: [],
count: 1,
},
],
},
});
const mockMembers = new Map<string, PathAccessRole>();
const pubkey = 'bbaareieswor4fnmzdwmv6fwij2rxyyjmpc2izognkiqnfxlvnzzsvs7y5y';
mockMembers.set(pubkey, PathAccessRole.PATH_ACCESS_ROLE_WRITER);
when(mockBuckets.pullPathAccessRoles(anyString(), anyString())).thenResolve(mockMembers);
const result = await storage.listDirectory(listDirectoryRequest);
const expectedDate = dayjs(new Date(Math.round(updatedAt / 1000000))).format();
expect(result).to.not.equal(undefined);
expect(result.items[0]).to.not.equal(undefined);
expect(result.items[0].name).to.equal(childItem.name);
expect(result.items[0].bucket).to.not.be.empty;
expect(result.items[0].dbId).to.not.be.empty;
expect(result.items[0].ipfsHash).to.equal(childItem.cid);
expect(result.items[0].isDir).to.equal(childItem.isDir);
expect(result.items[0].sizeInBytes).to.equal(childItem.size);
expect(result.items[0].created).to.equal(expectedDate);
expect(result.items[0].updated).to.equal(expectedDate);
expect(result.items[0].fileExtension).to.equal('');
expect(result.items[0].isLocallyAvailable).to.equal(false);
expect(result.items[0].backupCount).to.equal(1);
expect(result.items[0].members).to.deep.equal([{
publicKey: Buffer.from(tryParsePublicKey(pubkey).pubKey).toString('hex'),
role: PathAccessRole.PATH_ACCESS_ROLE_WRITER,
address: GetAddressFromPublicKey(pubkey),
}]);
expect(result.items[0].isBackupInProgress).to.equal(false);
expect(result.items[0].isRestoreInProgress).to.equal(false);
expect(result.items[0].uuid).to.equal('generated-uuid');
});
});
describe('openFile()', () => {
// it('should throw error if user is not authenticated', async () => {
// const storage = new UserStorage({ identity: mockIdentity, token: '' });
// await expect(storage.openFile({ bucket: 'bucket', path: '' })).to.eventually.be.rejectedWith(
// UnauthenticatedError,
// );
// });
it('should throw if file is not found', async () => {
const { storage, mockBuckets } = initStubbedStorage();
when(mockBuckets.pullPath('myBucketKey', '/file.txt', anything())).thenThrow(
new Error('Error: no link named "file.txt" under QmVQWu2C3ZgdoAmBsffFASrgynAfgvYX8CCK4o9SxRvC4p'),
);
await expect(storage.openFile({ bucket: 'personal', path: '/file.txt' })).to.eventually.be.rejectedWith(
DirEntryNotFoundError,
);
});
it('should return a valid stream of files data', async () => {
const { storage, mockBuckets } = initStubbedStorage();
const actualFileContent = "file.txt's file content";
when(mockBuckets.pullPath('myBucketKey', '/file.txt', anything())).thenReturn(
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
newEncryptedDataWriter(actualFileContent, decodeFileEncryptionKey(encryptionKey)),
);
const result = await storage.openFile({ bucket: 'personal', path: '/file.txt' });
const filesData = await result.consumeStream();
expect(new TextDecoder('utf8').decode(filesData)).to.equal(actualFileContent);
expect(result.mimeType).to.equal('generic/type');
});
});
describe('openFileByUuid', () => {
// it('should throw if uuid is not found', async () => {
// // fix this when mocking metadatastore works
// });
it('should return a valid stream of files data', async () => {
const { storage, mockBuckets } = initStubbedStorage();
const fileUuid = v4();
const actualFileContent = "file.txt's file content";
when(mockBuckets.existing('mockThreadId')).thenReturn(Promise.resolve([
{
...mock<Root>(),
name: 'myBucket',
key: 'myBucketKey',
},
]));
when(mockBuckets.listPath('myBucketKey', anyString())).thenResolve({
item: {
...mock<PathItem>(),
name: 'file.txt',
path: '/ipfs/Qm123/file.txt',
metadata: {
updatedAt: (new Date().getMilliseconds()) * 1000000,
roles: new Map(),
},
items: [],
},
});
when(mockBuckets.pullPath('myBucketKey', anyString(), anything())).thenReturn(
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
newEncryptedDataWriter(actualFileContent, decodeFileEncryptionKey(encryptionKey)),
);
const mockMembers = new Map<string, PathAccessRole>();
mockMembers.set('dummykey', PathAccessRole.PATH_ACCESS_ROLE_WRITER);
when(mockBuckets.pullPathAccessRoles('myBucketKey', '/ipfs/Qm123/file.txt')).thenResolve(mockMembers);
const result = await storage.openFileByUuid({ uuid: fileUuid });
const filesData = await result.consumeStream();
expect(new TextDecoder('utf8').decode(filesData)).to.equal(actualFileContent);
expect(result.mimeType).to.equal('generic/type');
expect(result.entry.bucket).to.not.be.empty;
expect(result.entry.dbId).to.not.be.empty;
});
});
describe('addItems()', () => {
it('should publish data, error and done events correctly', async () => {
const { storage, mockBuckets } = initStubbedStorage();
const uploadError = new Error('update is non-fast-forward');
when(mockBuckets.pushPath('myBucketKey', anyString(), anything(), anything())).thenResolve({
...mock<PushPathResult>(),
});
const childItem = {
name: 'entryName',
path: '/ipfs/Qm123/entryName',
cid: 'Qm...',
isDir: false,
size: 10,
};
when(mockBuckets.listPath('myBucketKey', anyString())).thenResolve({
item: {
...mock<PathItem>(),
name: 'entryName',
path: '/ipfs/Qm123/entryName',
cid: 'Qm...',
isDir: false,
size: 10,
metadata: {
updatedAt: (new Date().getMilliseconds()) * 1000000,
roles: new Map<string, PathAccessRole>(),
},
count: 0,
items: [],
},
});
// fail upload of b.txt
when(mockBuckets.pushPath('myBucketKey', '/b.txt', anything(), anything())).thenReject(uploadError);
const callbackData = {
data: [] as AddItemsEventData[],
error: [] as AddItemsEventData[],
done: [] as AddItemsEventData[],
};
// upload files
const uploadResponse = await storage.addItems({
bucket: 'personal',
files: [
{
path: '/top/a.txt',
data: 'a content',
mimeType: 'text/plain',
},
{
path: 'b.txt',
data: 'b content',
mimeType: 'text/plain',
},
],
});
// listen for status events
uploadResponse.on('data', (it) => callbackData.data.push(it));
uploadResponse.on('error', (err) => callbackData.error.push(err));
await new Promise((resolve) => {
uploadResponse.once('done', (it) => {
callbackData.done.push(it);
resolve();
});
});
// verify callback data
expect(callbackData.data).to.containSubset([
{ path: '/top/a.txt', status: 'success' },
{ path: '/top', status: 'success' },
]);
expect(callbackData.error).to.containSubset([{ path: '/b.txt', status: 'error', error: uploadError }]);
expect(callbackData.done).to.containSubset([
{
bucket: 'personal',
files: [
{ path: '/top', status: 'success' },
{ path: '/top/a.txt', status: 'success' },
{ path: '/b.txt', status: 'error', error: uploadError },
],
},
]);
});
});
describe('shareViaPublicKey()', () => {
let storage: UserStorage;
let mockBuckets: Buckets;
beforeEach(() => {
const stub = initStubbedStorage();
storage = stub.storage;
mockBuckets = stub.mockBuckets;
});
it('should throw if public keys are empty', async () => {
await expect(
storage.shareViaPublicKey({
publicKeys: [],
paths: [
{
bucket: 'personal',
path: '/randomPath',
uuid: v4(),
},
],
}),
).to.eventually.be.rejected;
});
it('should throw if public keys are not valid', async () => {
await expect(
storage.shareViaPublicKey({
publicKeys: [{
id: '[email protected]',
pk: 'invalid-pk-provided',
}],
paths: [
{
bucket: 'personal',
path: '/randomPath',
uuid: v4(),
},
],
}),
).to.eventually.be.rejectedWith('Unsupported encoding: i');
});
});
});
Example #3
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');
});
});
});
Example #4
Source File: post.controller.spec.ts From nestjs-rest-sample with GNU General Public License v3.0 | 4 votes |
describe('Post Controller', () => {
describe('Replace PostService in provider(useClass: PostServiceStub)', () => {
let controller: PostController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: PostService,
useClass: PostServiceStub,
},
],
controllers: [PostController],
}).compile();
controller = await module.resolve<PostController>(PostController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('GET on /posts should return all posts', async () => {
const posts = await lastValueFrom(controller.getAllPosts());
expect(posts.length).toBe(3);
});
it('GET on /posts/:id should return one post ', (done) => {
controller.getPostById('1').subscribe((data) => {
expect(data._id).toEqual('1');
done();
});
});
it('POST on /posts should save post', async () => {
const post: CreatePostDto = {
title: 'test title',
content: 'test content',
};
const saved = await lastValueFrom(
controller.createPost(
post,
createMock<Response>({
location: jest.fn().mockReturnValue({
status: jest.fn().mockReturnValue({
send: jest.fn().mockReturnValue({
headers: { location: '/posts/post_id' },
status: 201,
}),
}),
}),
}),
),
);
// console.log(saved);
expect(saved.status).toBe(201);
});
it('PUT on /posts/:id should update the existing post', (done) => {
const post: UpdatePostDto = {
title: 'test title',
content: 'test content',
};
controller
.updatePost(
'1',
post,
createMock<Response>({
status: jest.fn().mockReturnValue({
send: jest.fn().mockReturnValue({
status: 204,
}),
}),
}),
)
.subscribe((data) => {
expect(data.status).toBe(204);
done();
});
});
it('DELETE on /posts/:id should delete post', (done) => {
controller
.deletePostById(
'1',
createMock<Response>({
status: jest.fn().mockReturnValue({
send: jest.fn().mockReturnValue({
status: 204,
}),
}),
}),
)
.subscribe((data) => {
expect(data).toBeTruthy();
done();
});
});
it('POST on /posts/:id/comments', async () => {
const result = await lastValueFrom(
controller.createCommentForPost(
'testpost',
{ content: 'testcomment' },
createMock<Response>({
location: jest.fn().mockReturnValue({
status: jest.fn().mockReturnValue({
send: jest.fn().mockReturnValue({
headers: { location: '/posts/post_id/comments/comment_id' },
status: 201,
}),
}),
}),
}),
),
);
expect(result.status).toBe(201);
});
it('GET on /posts/:id/comments', async () => {
const result = await lastValueFrom(
controller.getAllCommentsOfPost('testpost'),
);
expect(result.length).toBe(1);
});
});
describe('Replace PostService in provider(useValue: fake object)', () => {
let controller: PostController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: PostService,
useValue: {
findAll: (_keyword?: string, _skip?: number, _limit?: number) =>
of<any[]>([
{
_id: 'testid',
title: 'test title',
content: 'test content',
},
]),
},
},
],
controllers: [PostController],
}).compile();
controller = await module.resolve<PostController>(PostController);
});
it('should get all posts(useValue: fake object)', async () => {
const result = await lastValueFrom(controller.getAllPosts());
expect(result[0]._id).toEqual('testid');
});
});
describe('Replace PostService in provider(useValue: jest mocked object)', () => {
let controller: PostController;
let postService: PostService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: PostService,
useValue: {
constructor: jest.fn(),
findAll: jest
.fn()
.mockImplementation(
(_keyword?: string, _skip?: number, _limit?: number) =>
of<any[]>([
{
_id: 'testid',
title: 'test title',
content: 'test content',
},
]),
),
},
},
],
controllers: [PostController],
}).compile();
controller = await module.resolve<PostController>(PostController);
postService = module.get<PostService>(PostService);
});
it('should get all posts(useValue: jest mocking)', async () => {
const result = await lastValueFrom(controller.getAllPosts('test', 10, 0));
expect(result[0]._id).toEqual('testid');
expect(postService.findAll).toBeCalled();
expect(postService.findAll).lastCalledWith('test', 0, 10);
});
});
describe('Mocking PostService using ts-mockito', () => {
let controller: PostController;
const mockedPostService: PostService = mock(PostService);
beforeEach(async () => {
controller = new PostController(instance(mockedPostService));
});
it('should get all posts(ts-mockito)', async () => {
when(
mockedPostService.findAll(anyString(), anyNumber(), anyNumber()),
).thenReturn(
of([
{ _id: 'testid', title: 'test title', content: 'content' },
]) as Observable<Post[]>,
);
const result = await lastValueFrom(controller.getAllPosts('', 10, 0));
expect(result.length).toEqual(1);
expect(result[0].title).toBe('test title');
verify(
mockedPostService.findAll(anyString(), anyNumber(), anyNumber()),
).once();
});
});
});