How to mock fs.readFileSync with jest

Viewed 9048

in my app.js I have this function:

const bodyParser = require('body-parser')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const dataFilePath = '../shoppinglist/data.json'
const baseUrl = '/api/v1/shoppingLists'
let client
const fileSystem = require('fs')
let data



app.post(baseUrl, (req, res) => {
    const newData = req.body
    if(newData != null && !isEmpty(newData) && isRequiredFieldGiven(newData)){
        readUpdatedData()
        newData.id = getNewestId()
        data.data.push(newData)
        //updateData(data)
        console.log(data)
        res.setHeader('Content-Type', 'application/json')
        res.statusCode = 201
        res.json({"Location" : baseUrl + '/' + newData.id})
    }else{
        res.statusCode = 400
        res.send()
    }
})

function readUpdatedData(){
    let rawData = fileSystem.readFileSync(dataFilePath)
    data = JSON.parse(rawData)
}

in the testfile, I'm doing this to test an API post call which is using the readUpdatedData in it:

const request = require('supertest')
const shoppingListDataPath = ('../shoppinglist/data.json')
const baseUrl = '/api/v1/shoppingLists'
const appPath = '../src/app'

describe('create list entry', () => {
it('should return 201', async () => {
   let fs = require('fs')
 jest.spyOn(fs, 'readFileSync').mockReturnValueOnce(JSON.stringify({"some" : "data"}))

    let {app} = require(appPath)
        const entry = {
            "id": 1,
            "name": "filled shopping list2",
            "location": "lidl2",
            "targetDate": "22.03.1986",
            "priority": 1,
            "isFinished": false,
            "items": [{"count": 1, "name": "vodka"}, {"count": 1, "name": "vodka"}
            ]
        }
        const res = await request(app)
            .post(baseUrl)
            .send(entry)
        expect(res.statusCode).toEqual(201)
        expect(res.body).toEqual({"Location": baseUrl + 1})
    })
})

When I'm using mockImplementationOnce or mockReturnValueOnce, I've get an error 500 while it's calling readFileSynch. I've changed it to mockImplementation or/and mockReturnValue, then i've got an error 400. It doesn't call then the app.post all.

I've also tried with jest.fn() but was the same result.

1 Answers
Related