首页 > 解决方案 > 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:

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 | })

标签: node.jspostgresqlunit-testingjestjspg-promise

解决方案


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

推荐阅读