gpt4 book ai didi

javascript - JS/JestJS : How to test for a async mocked function?

转载 作者:行者123 更新时间:2023-11-29 18:57:53 25 4
gpt4 key购买 nike

正如您在我的测试文件中看到的那样,我已经模拟了所有 mongoDB 方法。

现在我需要测试 Content.update() 是否被调用。在此示例代码中,我正在测试一个名为 console.log 的文件,它正在运行,但不是我想要的。我不明白为什么我不能测试 update()

/category.test.js

import { updateCategory } from './category'
import DB from './lib/db'

test('should update document', async () => {
DB.getDB = jest.fn(
() => ({
get: jest.fn(
() => ({
findOne: jest.fn(() => ({ some: 'content' })),
update: jest.fn()
})
)
})
)
console.log = jest.fn()

return updateCategory({}, {
id: '12345678901234567'
}).then(() => {
expect(console.log).toHaveBeenCalled()
// instead check if `Content.update()` has been called
expect(DB.getDB().get().update).toHaveBeenCalled() // throws `Expected mock function to have been called.`
})
})

/category.js

import DB from './lib/db'

export async function updateCategory (obj, { id }) {
const db = DB.getDB()
const Content = db.get('content')
const doc = await Content.findOne({ _id: id })

console.log('ok');

await Content.update(
{ _id: id },
{ $set: { category: 'new category' } }
)
}

最佳答案

将你想要监视的 mock 存储在一个变量中,以便你可以跟踪它:

import { updateCategory } from './category'
import DB from './lib/db'
jest.mock('./lib/db');

const mockUpdate = jest.fn();

test('should update document', async () => {
DB.getDB.mockImplementation( // <-- available when you call jest.mock above, seems safer than overwriting the implementation in the real import
() => ({
get: jest.fn(
() => ({
findOne: jest.fn(() => ({ some: 'content' })),
update: mockUpdate
})
)
})
)
console.log = jest.fn()

return updateCategory({}, {
id: '12345678901234567'
}).then(() => {
expect(console.log).toHaveBeenCalled()
// instead check if `Content.update()` has been called
expect(mockUpdate).toHaveBeenCalled() // should work now
})
})

关于javascript - JS/JestJS : How to test for a async mocked function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48388010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com