node.js - jest always called 0 times
问题描述
I am a bit of a jest testing noob, but I am trying to mock some simple default functions.
Also note: this code works perfectly fine production running outside of test suite
// I am testing this simple util function:
import postgreSQL from 'pg-promise'
const postgres = postgreSQL({
// Initialization Options here...
})
const connection = `url`
export default postgres(connection)
and I think I am testing it correcty:
const postgres = jest.fn().mockImplementation(() => ({
one: async () => 'query'
}))
jest.mock('pg-promise', () => {
return {
__esModule: true,
default: () => postgres // jest.fn().mockImplementation(() => postgres)
}
})
// file being tested
import connectDb from './connection'
describe('Database Connection', () => {
beforeEach(() => {
//
})
afterEach(() => {
jest.restoreAllMocks()
})
it('should call connection with url', async () => {
let error = ''
try {
// file being tested
await connectDb.one('SELECT * from accounts LIMIT 1;')
} catch (err) {
error = err.message
}
expect(error).toEqual('')
expect(postgres).toHaveBeenCalledWith('url')
})
})
It looks like it should work:
pg-promise
library returns a default function that returnpostgres
functionpostgres(connection)
gets called with"url"
and returns a mocked{ one: async () => 'query' }
postgres(connection).one(...)
gets called
but jest is saying that postgres(connection)
never happens:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "url"
Number of calls: 0
46 |
47 | expect(error).toEqual('')
> 48 | expect(postgres).toHaveBeenCalledWith('url')
| ^
49 | })
50 | })
- `postgres(
解决方案
I dont know why this broke the test, but I fixed it by changing my npm run test
script:
before:
// package.json
"test": "jest --resetMocks --forceExit",
after:
// package.json
"test": "jest", // everything passes, my test works
推荐阅读
- c++ - 函数中的sizeof
- ios - 以编程方式为 iPhone 和 iPad 布局 UI 的最佳实践
- git - 为什么 React Native 模块的默认 Github 存储库经常分叉?
- ios - 限制 MKAnnotationView 仅在已绘制的折线上/与已绘制的折线一起拖动
- php - Laravel 资源控制器 show() 返回图片流
- asp.net-mvc - MVC 布局未清除,重定向内容加载在原始布局内
- javascript - 使用 XMLHttpRequest 的 Rapidapi Api 请求
- perl - Getopts 标记不带破折号的错误选项
- php - 将第二个表中的第二个(条件)结果添加到 SQL 查询
- annotations - PowerMockito:@PrepareForTest programaticcaly?