【发布时间】:2018-06-26 04:11:59
【问题描述】:
这就是我使用monk() 连接到 mongoDB 的方式。我会把它存储在state。
假设我们要删除一些集合,我们调用dropDB。
db.js
var state = {
db: null
}
export function connection () {
if (state.db) return
state.db = monk('mongdb://localhost:27017/db')
return state.db
}
export async function dropDB () {
var db = state.db
if (!db) throw Error('Missing database connection')
const Users = db.get('users')
const Content = db.get('content')
await Users.remove({})
await Content.remove({})
}
我不太确定使用state 变量是否是一种好方法。也许有人可以对此发表评论或显示改进。
现在我想用 JestJS 为这个函数写一个单元测试:
db.test.js
import monk from 'monk'
import { connection, dropDB } from './db'
jest.mock('monk')
describe('dropDB()', () => {
test('should throw error if db connection is missing', async () => {
expect.assertions(1)
await expect(dropDB()).rejects.toEqual(Error('Missing database connection'))
})
})
这部分很简单,但是下一部分给我带来了两个问题:
如何模拟remove() 方法?
test('should call remove() methods', async () => {
connection() // should set `state.db`, but doesn't work
const remove = jest.fn(() => Promise.resolve({ n: 1, nRemoved: 1, ok: 1 }))
// How do I use this mocked remove()?
expect(remove).toHaveBeenCalledTimes(2)
})
在那之前呢?如何设置state.db?
更新
正如 poke 所解释的,全局变量会造成问题。于是我换了一个班:
db.js
export class Db {
constructor() {
this.connection = monk('mongdb://localhost:27017/db');
}
async dropDB() {
const Users = this.connection.get('users');
const Content = this.connection.get('content');
await Users.remove({});
await Content.remove({});
}
}
这会产生这个测试文件:
db.test.js
import { Db } from './db'
jest.mock('./db')
let db
let remove
describe('DB class', () => {
beforeAll(() => {
const remove = jest.fn(() => Promise.resolve({ n: 1, nRemoved: 1, ok: 1 }))
Db.mockImplementation(() => {
return { dropDB: () => {
// Define this.connection.get() and use remove as a result of it
} }
})
})
describe('dropDB()', () => {
test('should call remove method', () => {
db = new Db()
db.dropDB()
expect(remove).toHaveBeenCalledTimes(2)
})
})
})
如何模拟任何this 元素?在这种情况下,我需要模拟 this.connection.get()
【问题讨论】:
-
您在呼叫连接吗?我没有看到“连接”的调用。
标签: javascript node.js mongodb unit-testing jestjs