Skip to content

Commit

Permalink
setup testing framework
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlwn123 committed Feb 13, 2024
1 parent 8238d4d commit 5a00193
Show file tree
Hide file tree
Showing 24 changed files with 9,574 additions and 4,561 deletions.
3 changes: 3 additions & 0 deletions __mocks__/@auth/prisma-adapter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
PrismaAdapter: jest.fn().mockReturnValue({})
}
1 change: 1 addition & 0 deletions __mocks__/@opensearch-project/opensearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default {}
151 changes: 151 additions & 0 deletions __mocks__/apollo-mocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { BLOCK_HEIGHT } from '../fragments/blockHeight'
import { CHAIN_FEE } from '../fragments/chainFee'
import { PRICE } from '../fragments/price'
import { SUB_FIELDS, SUB_FULL } from '../fragments/subs'
import { ME } from '../fragments/users'
const mockUser = {
me: {
id: 'user-123',
name: 'John Doe',
bioId: 'bio-456',
privates: {
autoDropBolt11s: true,
diagnostics: false,
fiatCurrency: 'USD',
greeterMode: true,
hideCowboyHat: false,
hideFromTopUsers: true,
hideInvoiceDesc: false,
hideIsContributor: true,
hideWalletBalance: false,
hideWelcomeBanner: true,
imgproxyOnly: false,
lastCheckedJobs: new Date().toISOString(), // Assuming ISO string format for dates
nostrCrossposting: true,
noteAllDescendants: false,
noteTerritoryPosts: true,
noteCowboyHat: false,
noteDeposits: true,
noteEarning: false,
noteForwardedSats: true,
noteInvites: false,
noteItemSats: true,
noteJobIndicator: false,
noteMentions: true,
sats: 1000,
tipDefault: 100,
tipPopover: true,
turboTipping: false,
upvotePopover: true,
wildWestMode: false,
withdrawMaxFeeDefault: 500,
lnAddr: 'lnbc1...',
autoWithdrawMaxFeePercent: 1,
autoWithdrawThreshold: 100000
},
optional: {
isContributor: true,
stacked: 5000,
streak: 10
}
}
}

const mockPrice = {
data: {
price: 123.45,
createdAt: Date.now()
}
}
const mockBlockHeight = {
data: {
blockHeight: 123456
}
}
const mockChainFee = {
data: {
chainFee: 0
}
}

const mockSubFields = {
name: 'ExampleSub',
postTypes: ['text', 'image', 'video'],
allowFreebies: true,
rankingType: 'engagement',
billingType: 'subscription',
billingCost: 5.99,
billingAutoRenew: true,
billedLastAt: '2023-01-01T00:00:00Z',
baseCost: 4.99,
userId: 'user-123',
desc: 'This is an example description of the sub.',
status: 'active',
moderated: false,
moderatedCount: 10,
meMuteSub: false,
nsfw: false
}

const mockSubFull = {
...mockSubFields,
user: {
name: 'User Name',
id: 'user-123',
optional: {
streak: 5
}
}
}

export default [
{
request: {
operationName: 'price',
query: PRICE,
variables: {
fiatCurrency: undefined
},
result: mockPrice
}
},
{
request: {
operationName: 'me',
query: ME,
result: mockUser
}
},
{
request: {
operationName: 'blockHeight',
query: BLOCK_HEIGHT,
result: mockBlockHeight
}
},
{
request: {
operationName: 'chainFee',
query: CHAIN_FEE,
result: mockChainFee,
maxUsageCount: Number.POSITIVE_INFINITY
}
},
{
request: {
operationName: 'subFields',
query: SUB_FIELDS,
result: mockSubFields,
maxUsageCount: Number.POSITIVE_INFINITY
}
},
{
request: {
operationName: 'subFull',
query: SUB_FULL,
result: mockSubFull,
maxUsageCount: Number.POSITIVE_INFINITY
}
}

]
1 change: 1 addition & 0 deletions __mocks__/fileMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = () => 'mock file'
17 changes: 17 additions & 0 deletions __mocks__/ln-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module.exports = {
getIdentity: jest.fn().mockResolvedValue({ publicKey: '123' }),
createHodlInvoice: jest.fn().mockResolvedValue(),
createInvoice: jest.fn().mockResolvedValue(),
decodePaymentRequest: jest.fn().mockResolvedValue(),
payViaPaymentRequest: jest.fn().mockResolvedValue(),
cancelHodlInvoice: jest.fn().mockResolvedValue(),
getInvoice: jest.fn().mockResolvedValue(),
getNode: jest.fn().mockResolvedValue(),
authenticatedLndGrpc: jest.fn().mockResolvedValue({
lnd: {}
}),
getHeight: jest.fn().mockResolvedValue({ current_block_height: 0 }),
getChainFeeRate: jest.fn().mockResolvedValue({ tokens_per_vbyte: 0 }),
getWalletInfo: jest.fn().mockResolvedValue({}),
settleHodlInvoice: jest.fn().mockResolvedValue({})
}
3 changes: 3 additions & 0 deletions __mocks__/mdast-util-find-and-replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
findAndReplace: (tree) => tree
}
3 changes: 3 additions & 0 deletions __mocks__/mdast-util-gfm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
findAndReplace: (tree) => tree
}
20 changes: 20 additions & 0 deletions __mocks__/next-auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export class AuthError extends Error {
type
constructor (type) {
super(type)
this.type = type
}
}

const NextAuth = () => ({
auth: jest.fn(),
signIn: jest.fn(),
signOut: jest.fn(),
handlers: {
GET: jest.fn(),
POST: jest.fn()
},
AuthError
})

export default NextAuth
3 changes: 3 additions & 0 deletions __mocks__/next-auth/jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
getToken: jest.fn().mockResolvedValue({})
}
22 changes: 22 additions & 0 deletions __mocks__/next-auth/next.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export class AuthError extends Error {
type
constructor (type) {
super(type)
this.type = type
}
}

const NextAuth = () => ({
auth: jest.fn(),
signIn: jest.fn(),
signOut: jest.fn(),
handlers: {
GET: jest.fn(),
POST: jest.fn()
},
AuthError
})

export const getServerSession = jest.fn().mockResolvedValue({})

export default NextAuth
7 changes: 7 additions & 0 deletions __mocks__/next-auth/providers/credentials.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = () => ({
id: 'credentials',
name: 'Credentials',
type: 'credentials',
credentials: {},
authorize: () => jest.fn().mockReturnedValue({})
})
9 changes: 9 additions & 0 deletions __mocks__/next-auth/providers/email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = () => ({
id: 'email',
name: 'email',
type: 'Email',
server: {},
from: '',
maxAge: 24 * 60 * 60,
sendVerificationRequest: jest.fn().mockResolvedValue({})
})
8 changes: 8 additions & 0 deletions __mocks__/next-auth/providers/github.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = () => ({
id: 'github',
name: 'GitHub',
type: 'oauth',
authorization: {},
token: '',
userinfo: {}
})
8 changes: 8 additions & 0 deletions __mocks__/next-auth/providers/twitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = () => ({
id: 'twitter',
name: 'Twitter',
type: 'oauth',
authorization: {},
token: '',
userinfo: {}
})
6 changes: 6 additions & 0 deletions __mocks__/react-markdown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
__esModule: true,
default: (props) => {
return <>{props.children}</>
}
}
26 changes: 26 additions & 0 deletions __tests__/__snapshots__/sample.spec.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Sample Test should create snapshot: Hello World snapshot should render 1`] = `
<div>
<div
class="toast-container bottom-0 end-0 position-fixed pb-3 pe-3 toastContainer"
/>
<div>
Hello World
</div>
</div>
`;

exports[`Sample Test should render the loading screen: Loading Screen should render 1`] = `
<div>
<div
class="toast-container bottom-0 end-0 position-fixed pb-3 pe-3 toastContainer"
/>
<div
class="d-flex justify-content-center mt-3 mb-1"
data-testid="page-loading"
>
mock file
</div>
</div>
`;
26 changes: 26 additions & 0 deletions __tests__/sample.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { render, screen } from 'test-utils'
import Home from '../pages/~'
import { waitFor } from '@testing-library/react'

describe('Sample Test', () => {
it('should be true', () => {
expect(true).toBe(true)
})

it('should render "Hello World"', () => {
render(<div>Hello World</div>)
expect(screen.getByText('Hello World')).toBeInTheDocument()
})

it('should create snapshot', () => {
const { container } = render(<div>Hello World</div>)
expect(container).toMatchSnapshot('Hello World snapshot should render')
})

it('should render the loading screen', async () => {
const { container } = render(<Home />)
const loading = await waitFor(() => screen.getByTestId('page-loading'))
expect(loading).toBeInTheDocument()
expect(container).toMatchSnapshot('Loading Screen should render')
})
})
2 changes: 1 addition & 1 deletion components/page-loading.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Moon from '../svgs/moon-fill.svg'

export default function PageLoading () {
return (
<div className='d-flex justify-content-center mt-3 mb-1'>
<div data-testid='page-loading' className='d-flex justify-content-center mt-3 mb-1'>
<Moon className='spin fill-grey' />
</div>
)
Expand Down
31 changes: 31 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const nextJest = require('next/jest')

const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './'
})

// Add any custom config to be passed to Jest
/** @type {import("jest").Config} */
const config = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest/jest.setup.jsx'],
moduleFileExtensions: ['js', 'jsx'],
moduleNameMapper: {
'^test-utils$': '<rootDir>/jest/test-utils.jsx',
'^.+\\.(svg)$': '<rootDir>/__mocks__/fileMock.js'
}
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
// https://stackoverflow.com/a/75604417/21032284
module.exports = async () => {
const jestConfig = await createJestConfig(config)()
const out = {
...jestConfig,
transformIgnorePatterns: [
'(?!(/node_modules/(next|github-slugger|react-markdown|vfile|vfile-message|unist-.*|unified|bail|is-plain-obj|trough|remark-.*|mdast-util-.*|micromark.*|decode-named-character-reference|character-entities|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|pretty-bytes)/))(/node_modules/.+.(js|jsx|mjs|cjs|ts|tsx)$)'
]
}
return out
}
10 changes: 10 additions & 0 deletions jest/jest.setup.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/* eslint-env jest */

require('@testing-library/jest-dom')
global.MessageChannel = require('worker_threads').MessageChannel
global.TextEncoder = require('util').TextEncoder
global.TextDecoder = require('util').TextDecoder

global.os = 'iOS'

jest.mock('next/router', () => require('next-router-mock'))
Loading

0 comments on commit 5a00193

Please sign in to comment.