Updating test cases - trying to get everything in order for merge.

This commit is contained in:
mike12345567 2022-11-14 20:25:05 +00:00
parent 380ee221b1
commit 1af47003c5
10 changed files with 134 additions and 95 deletions

View File

@ -58,7 +58,7 @@
"testEnvironment": "node", "testEnvironment": "node",
"moduleNameMapper": { "moduleNameMapper": {
"@budibase/types": "<rootDir>/../types/src", "@budibase/types": "<rootDir>/../types/src",
"axios": "axios/dist/node/axios.cjs" "^axios.*$": "<rootDir>/node_modules/axios/lib/axios.js"
}, },
"setupFiles": [ "setupFiles": [
"./scripts/jestSetup.ts" "./scripts/jestSetup.ts"

View File

@ -66,7 +66,20 @@ const checkInitialised = () => {
export function getPouchDB(dbName: string, opts?: any): PouchDB.Database { export function getPouchDB(dbName: string, opts?: any): PouchDB.Database {
checkInitialised() checkInitialised()
return new Pouch(dbName, opts) const db = new Pouch(dbName, opts)
const dbPut = db.put
db.put = async (doc: any, options = {}) => {
if (!doc.createdAt) {
doc.createdAt = new Date().toISOString()
}
doc.updatedAt = new Date().toISOString()
return dbPut(doc, options)
}
db.exists = async () => {
const info = await db.info()
return !info.error
}
return db
} }
// use this function if you have called getPouchDB - close // use this function if you have called getPouchDB - close

View File

@ -1,19 +1,15 @@
import env from "../environment" import env from "../environment"
import { directCouchQuery, PouchLike } from "./couch" import { directCouchQuery, PouchLike, getPouchDB } from "./couch"
import { CouchFindOptions } from "@budibase/types" import { CouchFindOptions } from "@budibase/types"
let initialised = false
const dbList = new Set() const dbList = new Set()
const checkInitialised = () => {
if (!initialised) {
throw new Error("init has not been called")
}
}
export function getDB(dbName?: string, opts?: any): PouchLike { export function getDB(dbName?: string, opts?: any): PouchLike {
// TODO: once using the test image, need to remove this
if (env.isTest()) { if (env.isTest()) {
dbList.add(dbName) dbList.add(dbName)
// @ts-ignore
return getPouchDB(dbName, opts)
} }
return new PouchLike(dbName, opts) return new PouchLike(dbName, opts)
} }
@ -32,7 +28,6 @@ export function allDbs() {
if (!env.isTest()) { if (!env.isTest()) {
throw new Error("Cannot be used outside test environment.") throw new Error("Cannot be used outside test environment.")
} }
checkInitialised()
return [...dbList] return [...dbList]
} }

View File

@ -1,5 +1,5 @@
require("../../../tests/utilities/TestConfiguration") require("../../../tests/utilities/TestConfiguration")
const getUrlInfo = require("../pouch").getUrlInfo const getUrlInfo = require("../couch").getUrlInfo
describe("pouch", () => { describe("pouch", () => {
describe("Couch DB URL parsing", () => { describe("Couch DB URL parsing", () => {

View File

@ -1,4 +1,4 @@
require("../../../tests/utilities/TestConfiguration"); require("../../../tests/utilities/TestConfiguration")
const { const {
generateAppID, generateAppID,
getDevelopmentAppID, getDevelopmentAppID,
@ -8,8 +8,8 @@ const {
getPlatformUrl, getPlatformUrl,
getScopedConfig getScopedConfig
} = require("../utils") } = require("../utils")
const tenancy = require("../../tenancy"); const tenancy = require("../../tenancy")
const { Configs, DEFAULT_TENANT_ID } = require("../../constants"); const { Configs, DEFAULT_TENANT_ID } = require("../../constants")
const env = require("../../environment") const env = require("../../environment")
describe("utils", () => { describe("utils", () => {

View File

@ -2,7 +2,7 @@ module FetchMock {
const fetch = jest.requireActual("node-fetch") const fetch = jest.requireActual("node-fetch")
let failCount = 0 let failCount = 0
module.exports = async (url: any, opts: any) => { const func = async (url: any, opts: any) => {
function json(body: any, status = 200) { function json(body: any, status = 200) {
return { return {
status, status,
@ -106,4 +106,8 @@ module FetchMock {
} }
return fetch(url, opts) return fetch(url, opts)
} }
func.Headers = fetch.Headers
module.exports = func
} }

View File

@ -43,7 +43,7 @@
"@budibase/backend-core/(.*)": "<rootDir>/../backend-core/$1", "@budibase/backend-core/(.*)": "<rootDir>/../backend-core/$1",
"@budibase/backend-core": "<rootDir>/../backend-core/src", "@budibase/backend-core": "<rootDir>/../backend-core/src",
"@budibase/types": "<rootDir>/../types/src", "@budibase/types": "<rootDir>/../types/src",
"axios": "axios/dist/node/axios.cjs" "^axios.*$": "<rootDir>/node_modules/axios/lib/axios.js"
}, },
"setupFiles": [ "setupFiles": [
"./scripts/jestSetup.js" "./scripts/jestSetup.js"

View File

@ -1,32 +1,36 @@
const TestConfig = require("../../tests/utilities/TestConfiguration") const TestConfig = require("../../tests/utilities/TestConfiguration")
const { basicTable } = require("../../tests/utilities/structures") const { basicTable } = require("../../tests/utilities/structures")
const linkUtils = require("../linkedRows/linkUtils") const linkUtils = require("../linkedRows/linkUtils")
const { getAppDB } = require("@budibase/backend-core/context") const { context } = require("@budibase/backend-core")
const { doWithDB } = require("@budibase/backend-core/db")
describe("test link functionality", () => { describe("test link functionality", () => {
const config = new TestConfig(false) const config = new TestConfig(false)
let appId
describe("getLinkedTable", () => { describe("getLinkedTable", () => {
let db, table let table
beforeEach(async () => { beforeEach(async () => {
await config.init() const app = await config.init()
db = getAppDB() appId = app.appId
table = await config.createTable() table = await config.createTable()
}) })
it("should be able to retrieve a linked table from a list", async () => { it("should be able to retrieve a linked table from a list", async () => {
await context.doInAppContext(appId, async () => {
const retrieved = await linkUtils.getLinkedTable(table._id, [table]) const retrieved = await linkUtils.getLinkedTable(table._id, [table])
expect(retrieved._id).toBe(table._id) expect(retrieved._id).toBe(table._id)
}) })
})
it("should be able to retrieve a table from DB and update list", async () => { it("should be able to retrieve a table from DB and update list", async () => {
const tables = [] const tables = []
await context.doInAppContext(appId, async () => {
const retrieved = await linkUtils.getLinkedTable(table._id, tables) const retrieved = await linkUtils.getLinkedTable(table._id, tables)
expect(retrieved._id).toBe(table._id) expect(retrieved._id).toBe(table._id)
expect(tables[0]).toBeDefined() expect(tables[0]).toBeDefined()
}) })
}) })
})
describe("getRelatedTableForField", () => { describe("getRelatedTableForField", () => {
let link = basicTable() let link = basicTable()
@ -48,15 +52,14 @@ describe("test link functionality", () => {
describe("getLinkDocuments", () => { describe("getLinkDocuments", () => {
it("should create the link view when it doesn't exist", async () => { it("should create the link view when it doesn't exist", async () => {
// create the DB and a very basic app design DB // create the DB and a very basic app design DB
const output = await doWithDB("test", async db => { await context.doInAppContext(appId, async () => {
await db.put({ _id: "_design/database", views: {} }) const output = await linkUtils.getLinkDocuments({
return await linkUtils.getLinkDocuments({
tableId: "test", tableId: "test",
rowId: "test", rowId: "test",
includeDocs: false, includeDocs: false,
}) })
})
expect(Array.isArray(output)).toBe(true) expect(Array.isArray(output)).toBe(true)
}) })
}) })
}) })
})

View File

@ -1,16 +1,8 @@
require("../../db").init()
mockAuthWithNoCookie() mockAuthWithNoCookie()
mockWorker() mockWorker()
mockUserGroups() mockUserGroups()
jest.mock("@budibase/backend-core/db", () => {
const coreDb = jest.requireActual("@budibase/backend-core/db")
coreDb.init()
return {
...coreDb,
dbExists: async () => true,
}
})
function mockWorker() { function mockWorker() {
jest.mock("../../utilities/workerRequests", () => ({ jest.mock("../../utilities/workerRequests", () => ({
getGlobalSelf: () => { getGlobalSelf: () => {
@ -43,7 +35,14 @@ function mockUserGroups() {
function mockAuthWithNoCookie() { function mockAuthWithNoCookie() {
jest.resetModules() jest.resetModules()
mockWorker() mockWorker()
jest.mock("@budibase/backend-core/cache", () => ({ jest.mock("@budibase/backend-core", () => {
const core = jest.requireActual("@budibase/backend-core")
return {
...core,
db: {
dbExists: () => true,
},
cache: {
user: { user: {
getUser: () => { getUser: () => {
return { return {
@ -51,34 +50,36 @@ function mockAuthWithNoCookie() {
} }
}, },
}, },
})) },
jest.mock("@budibase/backend-core/utils", () => ({ utils: {
getAppIdFromCtx: jest.fn(), getAppIdFromCtx: jest.fn(),
setCookie: jest.fn(), setCookie: jest.fn(),
getCookie: jest.fn(), getCookie: jest.fn(),
})) },
jest.mock("@budibase/backend-core/constants", () => ({ }
Cookies: {}, })
}))
} }
function mockAuthWithCookie() { function mockAuthWithCookie() {
jest.resetModules() jest.resetModules()
mockWorker() mockWorker()
jest.mock("@budibase/backend-core/utils", () => ({ jest.mock("@budibase/backend-core", () => {
const core = jest.requireActual("@budibase/backend-core")
return {
...core,
db: {
dbExists: () => true,
},
utils: {
getAppIdFromCtx: () => { getAppIdFromCtx: () => {
return "app_test" return "app_test"
}, },
setCookie: jest.fn(), setCookie: jest.fn(),
clearCookie: jest.fn(), clearCookie: jest.fn(),
getCookie: () => ({ appId: "app_different", roleId: "PUBLIC" }), getCookie: () => ({ appId: "app_different", roleId: "PUBLIC" }),
}))
jest.mock("@budibase/backend-core/constants", () => ({
Cookies: {
Auth: "auth",
CurrentApp: "currentapp",
}, },
})) }
})
} }
class TestConfiguration { class TestConfiguration {
@ -88,7 +89,16 @@ class TestConfiguration {
this.ctx = { this.ctx = {
next: this.next, next: this.next,
throw: this.throw throw: this.throw,
request: {
body: {},
headers: {},
},
headers: {},
path: "",
cookies: {
set: jest.fn(),
}
} }
} }
@ -101,6 +111,8 @@ class TestConfiguration {
executeMiddleware() { executeMiddleware() {
// import as late as possible for mocks // import as late as possible for mocks
jest.resetModules()
require("../../db").init()
const currentAppMiddleware = require("../currentapp") const currentAppMiddleware = require("../currentapp")
return currentAppMiddleware(this.ctx, this.next) return currentAppMiddleware(this.ctx, this.next)
} }
@ -138,11 +150,11 @@ describe("Current app middleware", () => {
async function checkExpected(setCookie) { async function checkExpected(setCookie) {
config.setUser() config.setUser()
await config.executeMiddleware() await config.executeMiddleware()
let { setCookie: cookieFn } = require("@budibase/backend-core/utils") let { utils } = require("@budibase/backend-core")
if (setCookie) { if (setCookie) {
expect(cookieFn).toHaveBeenCalled() expect(utils.setCookie).toHaveBeenCalled()
} else { } else {
expect(cookieFn).not.toHaveBeenCalled() expect(utils.setCookie).not.toHaveBeenCalled()
} }
expect(config.ctx.roleId).toEqual("PUBLIC") expect(config.ctx.roleId).toEqual("PUBLIC")
expect(config.ctx.user.role._id).toEqual("PUBLIC") expect(config.ctx.user.role._id).toEqual("PUBLIC")
@ -157,31 +169,43 @@ describe("Current app middleware", () => {
it("should perform correct when no cookie exists", async () => { it("should perform correct when no cookie exists", async () => {
mockReset() mockReset()
jest.mock("@budibase/backend-core/utils", () => ({ jest.mock("@budibase/backend-core", () => {
const core = jest.requireActual("@budibase/backend-core")
return {
...core,
db: {
dbExists: () => true,
},
utils: {
getAppIdFromCtx: () => { getAppIdFromCtx: () => {
return "app_test" return "app_test"
}, },
setCookie: jest.fn(), setCookie: jest.fn(),
getCookie: jest.fn(), getCookie: jest.fn(),
})) },
jest.mock("@budibase/backend-core/constants", () => ({ }
Cookies: {}, })
}))
await checkExpected(true) await checkExpected(true)
}) })
it("lastly check what occurs when cookie doesn't need updated", async () => { it("lastly check what occurs when cookie doesn't need updated", async () => {
mockReset() mockReset()
jest.mock("@budibase/backend-core/utils", () => ({ jest.mock("@budibase/backend-core", () => {
const core = jest.requireActual("@budibase/backend-core")
return {
...core,
db: {
dbExists: () => true,
},
utils: {
getAppIdFromCtx: () => { getAppIdFromCtx: () => {
return "app_test" return "app_test"
}, },
setCookie: jest.fn(), setCookie: jest.fn(),
getCookie: () => ({ appId: "app_test", roleId: "PUBLIC" }), getCookie: () => ({ appId: "app_test", roleId: "PUBLIC" }),
})) },
jest.mock("@budibase/backend-core/constants", () => ({ }
Cookies: {}, })
}))
await checkExpected(false) await checkExpected(false)
}) })
}) })

View File

@ -99,7 +99,7 @@
"@budibase/backend-core/(.*)": "<rootDir>/../backend-core/$1", "@budibase/backend-core/(.*)": "<rootDir>/../backend-core/$1",
"@budibase/backend-core": "<rootDir>/../backend-core/src", "@budibase/backend-core": "<rootDir>/../backend-core/src",
"@budibase/types": "<rootDir>/../types/src", "@budibase/types": "<rootDir>/../types/src",
"axios": "axios/dist/node/axios.cjs" "^axios.*$": "<rootDir>/node_modules/axios/lib/axios.js"
}, },
"setupFiles": [ "setupFiles": [
"./scripts/jestSetup.js" "./scripts/jestSetup.js"