Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  80] [ 3]  / answers: 1 / hits: 13230  / 4 Years ago, sun, september 20, 2020, 12:00:00

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.


More From » node.js

 Answers
5

Mocking modules requires calling mock('modulename') like this:


jest.mock('fs');

See Mocking modules and Manual module mocks


[#2644] Wednesday, September 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;