vendredi 11 septembre 2020

Test function declared in other file with jest

I have a problem to test a function. The function is defined in app.js, the testfile is app.test.js How can I import the function, so that I can test it?

app.js

const app = express()
app.use(bodyParser.json())
const data = require('../shoppinglist/data.json')
const baseUrl = '/api/v1/shoppingLists'
module.exports = {app, client, listener, getNewestId}

function getNewestId(obj){
    let idArray = []
    for(let i = 0; i < obj.length; i++) {
        idArray.push(obj[i].id)
    }
    return Math.max(...idArray)
}

app.test.js

const appPath = '../src/app'
describe('getNewestId from Valid array', () => {
    it('should return id 3', async () => {
        jest.mock(shoppingListDataPath, () => [
            {
                "id": 1,
                "name": "filled shopping list",
                "location": "lidl",
                "targetDate": "22.03.1986",
                "priority": 1,
                "isFinished": false,
                "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
                ]
            }, {
                "id": 2,
                "name": "filled shopping list2",
                "location": "lidl2",
                "targetDate": "22.03.1986",
                "priority": 1,
                "isFinished": false,
                "items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
                ]
            }
        ])
        const {app} = require(appPath)
        app.getNewestId = jest.fn()
        expect(app.getNewestId()).toEqual(200)
    })
})

I guess it's something wrong with the requires / imports. But I can only use here require.

Aucun commentaire:

Enregistrer un commentaire