Best JavaScript code snippet using ng-mocks
refresh-token-unit.spec.ts
Source:refresh-token-unit.spec.ts
1import faker from 'faker';2import { sign } from 'jsonwebtoken';3import auth from '@config/auth';4import { TokenRepositoryInMemory } from '@modules/accounts/repositories/in-memory';5import { DayjsFacade } from '@shared/container/providers/date/implementations';6import { JwtFacade } from '@shared/container/providers/jwt/implementations';7import { serverError, unauthorized } from '@shared/http';8import { RefreshTokenController, RefreshTokenUseCase } from '.';9import { InvalidRefreshToken, UserTokenDoesNotExists } from './errors';10let tokenProvider: JwtFacade;11let dateProvider: DayjsFacade;12let tokenRepository: TokenRepositoryInMemory;13let refreshTokenUseCase: RefreshTokenUseCase;14let refreshTokenController: RefreshTokenController;15const id = faker.datatype.uuid();16const token = sign({}, auth.secret_refresh_token, {17 subject: id,18});19const token_mock = {20 id: faker.datatype.uuid(),21 id_user: id,22 token,23 expires_in: faker.date.soon(),24};25const http_request = {26 body: {27 token,28 },29};30describe('refresh token: unit', () => {31 beforeAll(() => {32 tokenProvider = new JwtFacade();33 dateProvider = new DayjsFacade();34 tokenRepository = new TokenRepositoryInMemory();35 refreshTokenUseCase = new RefreshTokenUseCase(36 tokenRepository,37 dateProvider,38 tokenProvider,39 );40 refreshTokenController = new RefreshTokenController(refreshTokenUseCase);41 });42 it('should refreshTokenUseCase call your methods correctly', async () => {43 await tokenRepository.save({44 ...token_mock,45 });46 const refresh_token = 'any_refresh_token';47 const expires_in = faker.date.future();48 const verifySpy = jest.spyOn(tokenProvider, 'verify');49 const decodeSpy = jest.spyOn(tokenProvider, 'decode');50 const findByUserIdAndTokenSpy = jest.spyOn(51 tokenRepository,52 'findByUserIdAndToken',53 );54 const deleteByIdSpy = jest.spyOn(tokenRepository, 'deleteById');55 const createTokenSpy = jest56 .spyOn(tokenProvider, 'createToken')57 .mockResolvedValueOnce(refresh_token);58 const addDaysSpy = jest59 .spyOn(dateProvider, 'addDays')60 .mockReturnValueOnce(expires_in);61 const saveSpy = jest.spyOn(tokenRepository, 'save');62 await refreshTokenUseCase.execute(token);63 expect(verifySpy).toBeCalledWith(token, auth.secret_refresh_token);64 expect(decodeSpy).toBeCalledWith(token);65 expect(findByUserIdAndTokenSpy).toBeCalledWith(id, token);66 expect(deleteByIdSpy).toBeCalledWith(token_mock.id);67 expect(createTokenSpy).toBeCalledTimes(2);68 expect(addDaysSpy).toBeCalledWith(auth.expires_refresh_token_days);69 expect(saveSpy).toBeCalledWith({70 expires_in,71 id_user: id,72 token: refresh_token,73 });74 });75 it('should refreshTokenController call your methods correctly', async () => {76 const executeSpy = jest.spyOn(refreshTokenUseCase, 'execute');77 await refreshTokenController.handle(http_request);78 expect(executeSpy).toBeCalledWith(token);79 });80 it('should accept a valid refresh token', async () => {81 await tokenRepository.save({82 ...token_mock,83 });84 const http_response = await refreshTokenController.handle(http_request);85 expect(http_response.statusCode).toBe(201);86 expect(http_response.body.access_token).toBeTruthy();87 expect(http_response.body.refresh_token).toBeTruthy();88 });89 it('should not accept a invalid refresh_token', async () => {90 const token = sign({}, 'invalid_secret');91 const invalid_http_request = {92 body: {93 token,94 },95 };96 const http_response = await refreshTokenController.handle(97 invalid_http_request,98 );99 expect(http_response).toEqual(unauthorized(new InvalidRefreshToken()));100 });101 it('should not accept a not registered refresh token', async () => {102 const http_response = await refreshTokenController.handle(http_request);103 expect(http_response).toEqual(unauthorized(new UserTokenDoesNotExists()));104 });105 it('should return a server error if refreshTokenUseCase throws a error', async () => {106 jest107 .spyOn(refreshTokenUseCase, 'execute')108 .mockRejectedValueOnce(new Error());109 const http_response = await refreshTokenController.handle(http_request);110 expect(http_response).toEqual(serverError());111 });...
user.controller.test.js
Source:user.controller.test.js
1'use strict'2const assert = require('chai').assert3const sinon = require('sinon')4const jwt = require('jsonwebtoken')5const { mockRequest, mockResponse } = require('mock-req-res')6const UserController = require('../../../src/controllers/user.controller')7const TOKEN_MOCK = 'TEST-TOKEN'8describe('Test controller/user.controller', () => {9 var req, res, next, error10 beforeEach(function (done) {11 req = mockRequest()12 req.body.username = 'test_user'13 res = mockResponse()14 next = sinon.stub()15 error = new Error('FAKE_ERROR')16 jwt.sign = sinon.stub().returns(TOKEN_MOCK)17 process.env.auth_jwtPrivateKey = '1234' // Mock jwt private key18 done()19 })20 it('should send token', async () => {21 await UserController.login(req, res, next)22 assert(res.send.calledWith(TOKEN_MOCK))23 })24 it('should call next() when error BODY_VALIDATE_ERROR', async () => {25 req.body.username = null26 await UserController.login(req, res, next)27 assert.strictEqual(next.args[0][0].message, 'BODY_VALIDATE_ERROR') // Use strictEqual and Error.message because this case throw error in try so can't mock error to use deepEqual28 assert.strictEqual(next.callCount, 1)29 })30 it('should call jwt.sign() once with object and jwtPrivatekey', async () => {31 await UserController.login(req, res, next)32 assert.strictEqual(jwt.sign.callCount, 1)33 assert.deepEqual(jwt.sign.args[0][0], { author: req.body.username })34 assert.strictEqual(jwt.sign.args[0][1], process.env.auth_jwtPrivateKey)35 })36 it('should call next() with error when error', async () => {37 jwt.sign = sinon.stub().throws(error)38 await UserController.login(req, res, next)39 assert.deepEqual(next.args[0][0], error)40 assert.strictEqual(next.callCount, 1)41 })...
Using AI Code Generation
1import { createToken } from 'ng-mocks';2const tokenMock = createToken('TOKEN_MOCK');3describe('TestComponent', () => {4 let component: TestComponent;5 let fixture: ComponentFixture<TestComponent>;6 beforeEach(async(() => {7 TestBed.configureTestingModule({8 {9 },10 }).compileComponents();11 }));12 beforeEach(() => {13 fixture = TestBed.createComponent(TestComponent);14 component = fixture.componentInstance;15 fixture.detectChanges();16 });17 it('should create', () => {18 expect(component).toBeTruthy();19 });20});
Using AI Code Generation
1const mock = require('ng-mocks');2const mock = require('ng-mocks');3const TOKEN_MOCK = mock.TOKEN_MOCK;4const mock = require('ng-mocks');5const TOKEN_MOCK = mock.TOKEN_MOCK;6const TOKEN_MOCK = mock.TOKEN_MOCK;7const mock = require('ng-mocks');8const TOKEN_MOCK = mock.TOKEN_MOCK;9const TOKEN_MOCK = mock.TOKEN_MOCK;10const TOKEN_MOCK = mock.TOKEN_MOCK;11const mock = require('ng-moc
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!