How to use stubRepository method in mountebank

Best JavaScript code snippet using mountebank

deviceService.test.ts

Source:deviceService.test.ts Github

copy

Full Screen

1import chai, { expect } from 'chai';2import sinonChai from 'sinon-chai';3import { ErrorCode } from '../../core/AppError';4import { Device } from './device';5import deviceService from './deviceService';6import { Repository } from '../../core/repository';7import { stubInterface } from 'ts-sinon';8import { Result } from '../../core/resolve';9import { QueryOptions } from 'mongoose-query-parser';10import faker from 'faker';11import { Types } from 'mongoose';12chai.use(sinonChai);13describe('DeviceService', function () {14 const stubRepository = stubInterface<Repository<Device>>();15 const service = deviceService(stubRepository);16 const makeValidInput = () => ({17 typeIdentifier: 'IPHONE_8',18 previewImageUrl: faker.internet.url(),19 });20 const makeDevice = (): Device => {21 const [device] = Device.create({22 typeIdentifier: 'IPHONE_8',23 previewImageUrl: faker.internet.url(),24 _id: new Types.ObjectId(),25 });26 return device!;27 };28 const resetStubRepository = () => {29 stubRepository.save.resetHistory();30 stubRepository.findById.resetHistory();31 stubRepository.find.resetHistory();32 stubRepository.delete.resetHistory();33 stubRepository.updateOne.resetHistory();34 stubRepository.save.callsFake(entity => {35 entity.id = new Types.ObjectId();36 return Promise.resolve(Result.ok(entity));37 });38 const entity = makeDevice();39 stubRepository.findById.resolves(Result.ok(entity));40 stubRepository.find.resolves(Result.ok([entity]));41 };42 beforeEach(function () {43 resetStubRepository();44 });45 describe('#createDevice', function () {46 it(`when creating with valid body, expect created Device.`, async function () {47 //Arrange48 const body = makeValidInput();49 //Act50 const [device] = await service.createDevice(body);51 //Assert52 expect(device).to.be.an.instanceOf(Device);53 });54 it(`when creating with invalid body, expect validation error.`, async function () {55 //Arrange56 const body = {};57 //Act58 const [, error] = await service.createDevice(body);59 //Assert60 expect(error).to.have.property('code').equal(ErrorCode.VALIDATION_ERROR);61 });62 });63 describe('#findSessions', function () {64 it(`when finding with a query, expect calling repository with it.`, async function () {65 //Arrange66 const stubQuery = stubInterface<QueryOptions>();67 //Act68 await service.findDevices(stubQuery);69 //Assert70 expect(stubRepository.find).to.have.been.calledWith(stubQuery);71 });72 });73 describe('#findDeviceById', function () {74 it(`when finding with an id and query, expect calling repository with both.`, async function () {75 //Arrange76 const stubQuery = stubInterface<QueryOptions>();77 const id = new Types.ObjectId().toHexString();78 //Act79 await service.findDeviceById(id, stubQuery);80 //Assert81 expect(stubRepository.findById).to.have.been.calledWith(id, stubQuery);82 });83 });84 describe('#deleteDevice', function () {85 it(`when deleting with an id, expect calling repository with it.`, async function () {86 //Arrange87 const id = new Types.ObjectId().toHexString();88 //Act89 await service.deleteDevice(id);90 //Assert91 expect(stubRepository.delete).to.have.been.calledWith(id);92 });93 });94 describe('#patchDevice', function () {95 it(`when updating with an id and a body, expect calling repository with both.`, async function () {96 //Arrange97 const body = {};98 const id = 'identifier';99 //Act100 await service.patchDevice(id, body);101 //Assert102 expect(stubRepository.updateOne).to.have.been.calledWith(id, body);103 });104 });...

Full Screen

Full Screen

stub.service.ts

Source:stub.service.ts Github

copy

Full Screen

1import { Injectable, HttpException, HttpStatus } from '@nestjs/common';2import { InjectRepository } from '@nestjs/typeorm';3import { CreateStubBodyDto } from './dto/create-stub-body.dto';4import { GetStubQueryDto } from './dto/get-stub-query.dto';5import { UpdateStubBodyDto } from './dto/update-stub-body.dto';6import { Stub } from './entities/stub.entity';7import { Repository } from 'typeorm';8@Injectable()9export class StubService {10 constructor(11 @InjectRepository(Stub) private readonly stubRepository: Repository<Stub>,12 ) {}13 14 async create(createStubBodyDto: CreateStubBodyDto) {15 console.debug("---------- stub.service.create() --------------------");16 // TODO - get user_uuid from the caller/security token17 // TODO: Add security check here to make sure the calling user can do this 18 return("Do Something in here")19 }20 findAll(getStubQueryDto: GetStubQueryDto) {21 console.debug("---------- stub.service.findAll() --------------------");22 return this.stubRepository.find();23 }24 findOne(stub_uuid: string) {25 console.debug("---------- stub.service.findOne(", stub_uuid, ") --------------------");26 return this.stubRepository.findOne( { where: {"stub_uuid": stub_uuid}} );27 }28 async update(stub_uuid: string, updateStubBodyDto: UpdateStubBodyDto) {29 console.debug("---------- stub.service.update(", stub_uuid, ")--------------------");30 // TODO: Add security check here to make sure the calling user can do this 31 // Confirm the given UUID actually exists32 const verifyUUID = await this.stubRepository.findOne( { where: {'stub_uuid': stub_uuid}});33 if (verifyUUID === null) {34 throw new HttpException('UUID Does not Exist', HttpStatus.BAD_REQUEST);35 }36 console.debug("BEFORE: ", verifyUUID);37 const result = await this.stubRepository.update(stub_uuid, updateStubBodyDto);38 console.debug(result);39 const afterUUID = await this.stubRepository.findOne( { where: {'stub_uuid': stub_uuid}});40 console.debug("After: ", afterUUID)41 return(afterUUID);42 }43 async remove(stub_uuid: string) {44 console.debug("---------- stub.service.remove(", stub_uuid, ")--------------------");45 // TODO: Add security check here to make sure the calling user can do this 46 // TODO: What logic do we actually want on this one - for now setting active -> FALSE47 // Confirm the given UUID actually exists48 const verifyUUID = await this.stubRepository.findOne({ where: { 'stub_uuid': stub_uuid } });49 if (verifyUUID === null) {50 throw new HttpException('UUID Does not Exist', HttpStatus.BAD_REQUEST);51 }52 console.debug("BEFORE: ", verifyUUID);53 const result = await this.stubRepository.update(stub_uuid, {'active': false});54 console.debug(result);55 const afterUUID = await this.stubRepository.findOne({ where: { 'stub_uuid': stub_uuid } });56 console.debug("After: ", afterUUID)57 return (afterUUID);58 }...

Full Screen

Full Screen

MacroBuilderDecorationTestSuite.js

Source:MacroBuilderDecorationTestSuite.js Github

copy

Full Screen

1import {TestSuite, testCase} from "WaveFunction";2import {MacroBuilder} from "Gluon";3import {assert} from "chai";4import sinon from "sinon";5export default class MacroBuilderDecorationTestSuite extends TestSuite {6 beforeEach() {7 this.builder = new MacroBuilder()8 }9 @testCase()10 'testTheMacroBuilderCanDecorateExtraMethodsOnARepositoryWithAVeryBeautifulName ^^! ' () {11 this.builder.when('foo');12 this.builder.when('foo bar');13 this.builder.when('FAR-boo');14 let stubRepository = {};15 let useMethodStub = sinon.stub(this.builder, 'use');16 this.builder.decorateRepositoryMethods(stubRepository);17 assert.isFunction(stubRepository.withFoo);18 assert.equal(stubRepository, stubRepository.withFoo('parameter1', 'parameter2'));19 assert(useMethodStub.calledWith('foo', 'parameter1', 'parameter2'));20 assert.isFunction(stubRepository.withFooBar);21 assert.equal(stubRepository, stubRepository.withFooBar('parameter1', 'parameter2'));22 assert(useMethodStub.calledWith('foo bar', 'parameter1', 'parameter2'));23 assert.isFunction(stubRepository.withFarBoo);24 assert.equal(stubRepository, stubRepository.withFarBoo('parameter1', 'parameter2'));25 assert(useMethodStub.calledWith('FAR-boo', 'parameter1', 'parameter2'));26 useMethodStub.restore();27 }28 @testCase()29 testTheMacroBuilderShouldThrowErrorWhenTheMethodIsAlreadyExisted() {30 this.builder.when('foo');31 let stubRepository = {withFoo: () => {}};32 assert.throws(() => {33 this.builder.decorateRepositoryMethods(stubRepository);34 }, 'E_MACRO_METHOD_EXISTED');35 }36 @testCase()37 testTheMacroBuilderShouldNotThrowErrorWhenTheDecoratedMethodNamesCollidedEachOtherButUseTheLastOneInstead() {38 this.builder.when('foo');39 this.builder.when('Foo');40 let stubRepository = {};41 let useMethodStub = sinon.stub(this.builder, 'use');42 this.builder.decorateRepositoryMethods(stubRepository);43 assert.isFunction(stubRepository.withFoo);44 assert.equal(stubRepository, stubRepository.withFoo());45 assert(useMethodStub.calledWith('Foo'));46 useMethodStub.restore();47 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2mb.create({3}, function (error, server) {4 if (error) {5 console.error(error);6 process.exit(1);7 }8 server.stubRepository.add({9 {10 equals: {11 }12 }13 {14 is: {15 headers: {16 },17 body: JSON.stringify({ message: 'Hello World' })18 }19 }20 }, function (error) {21 if (error) {22 console.error(error);23 process.exit(1);24 }25 });26});27const request = require('supertest');28const app = require('./app');29describe('Test', () => {30 it('should return Hello World', (done) => {31 request(app)32 .get('/test')33 .expect(200, { message: 'Hello World' }, done);34 });35});

Full Screen

Using AI Code Generation

copy

Full Screen

1const superagent = require('superagent');2const assert = require('assert');3const { promisify } = require('util');4const mb = require('mountebank');5const PORT = 2525;6const mbPost = promisify(superagent.post.bind(superagent));7describe('mountebank', () => {8 let server;9 let imposter;10 before(async () => {11 await mbPost(`${mbURL}/imposters`)12 .send({13 {14 {15 is: {16 }17 }18 }19 });20 server = await mb.create({ port: PORT });21 });22 after(async () => {23 await mbPost(`${mbURL}/imposters/${imposter.port}/stubs`)24 .send({25 {26 is: {27 }28 }29 });30 await server.stop();31 });32 it('should return Hello World', async () => {33 assert.strictEqual(response.text, 'Hello World');34 });35});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const stubs = require('./stubs.js');3const imposter = mb.create();4const port = 2525;5imposter.addStub(stubs.stubRepository);6imposter.post(port, () => {7 console.log('Imposter listening on port ${port}');8});9module.exports = {10 stubRepository: {11 predicates: [{12 equals: {13 }14 }],15 responses: [{16 is: {17 headers: {18 },19 body: [{

Full Screen

Using AI Code Generation

copy

Full Screen

1var stubRepository = require('./stubRepository');2stubRepository.createStub('testStub', 9000, 'localhost', 'testStub.json', function (err, response) {3 if (err) {4 console.log(err);5 }6 else {7 console.log(response);8 }9});10var request = require('request');11var fs = require('fs');12var path = require('path');13var mountebank = require('mountebank');14var mb = mountebank.create({ port: 2525, allowInjection: true });15var stubs = [];16var stub = {17 {18 "is": {19 "headers": {20 "Content-Type": "application/json; charset=UTF-8",21 },22 "body": {23 "data": {24 }25 }26 }27 }28};29stubs.push(stub);30var stubsPath = path.join(__dirname, 'stubs');31var stubsConfig = {32};33var stubsConfigPath = path.join(stubsPath, 'testStub.json');34var stubsConfigString = JSON.stringify(stubsConfig);35fs.writeFileSync(stubsConfigPath, stubsConfigString);36var createStub = function (stubName, port, host, stubConfig, callback) {37 var stubConfigPath = path.join(stubsPath, stubConfig);38 var stubConfigString = fs.readFileSync(stubConfigPath, 'utf8');39 var stubConfigJson = JSON.parse(stubConfigString);40 var options = {41 };42 request(options, function (error, response, body) {43 if (!error && response.statusCode == 201) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var config = require('./config.js');3var mb = config.mb;4var createImposter = function (imposter, cb) {5 var url = mb + '/imposters';6 request.post({7 }, function (error, response, body) {8 cb(error, response, body);9 });10};11var deleteImposter = function (port, cb) {12 var url = mb + '/imposters/' + port;13 request.del(url, function (error, response, body) {14 cb(error, response, body);15 });16};17var addStub = function (port, stub, cb) {18 var url = mb + '/imposters/' + port;19 request.put({20 }, function (error, response, body) {21 cb(error, response, body);22 });23};24var imposter = {25};26var stub = {27 responses: [{28 is: {29 }30 }]31};32createImposter(imposter, function (error, response, body) {33 if (error) {34 console.log(error);35 } else {36 addStub(imposter.port, stub, function (error, response, body) {37 if (error) {38 console.log(error);39 } else {40 deleteImposter(imposter.port, function (error, response, body) {41 if (error) {42 console.log(error);43 } else {44 console.log('Imposter deleted');45 }46 });47 }48 });49 }50});51module.exports = {52};53{54 "scripts": {55 },56 "dependencies": {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful