之前的一般问题。 当我使用jest.mock()时,我只能模拟整个模块吗?或还导出函数,常量。 在我的app.js中,例如使用const fileSystem = require('fs')。 我正在尝试测试该应用程序,该应用程序具有使用fs读取文件的方法。 我现在是否必须在测试中模拟'fs'模块或加载app.js,然后模拟fs加载的常量?
这是我的代码:
const express = require('express')
const dataFilePath = '../shoppinglist/data.json'
const fileSystem = require('fs')
let data
module.exports = {app, listener, getNewestId, getSmsFormatedShoppingList, readUpdatedData,
dataFilePath}
app.get(baseUrl, (req, res) => {
let finishedState
readUpdatedData()
if(isDataEmpty()){
return res.status(200).send([])
}
if(req.query.isFinished){
finishedState = req.query.isFinished === 'true'
}
const listsWithoutItems = data.data.map(({ items, ...rest }) => rest)
const filteredList = (finishedState === true || finishedState === false) ? sortShoppingListByFinished(listsWithoutItems, finishedState) : listsWithoutItems
if(filteredList.length === 0){
res.statusCode = 204
res.send()
}
// adjust later, this is just used for tests
res.setHeader('Content-Type', 'application/json')
data.data = filteredList
res.json(data)
res.status(200).send()
})
function readUpdatedData(){
let rawData = fileSystem.readFileSync(dataFilePath)
data = JSON.parse(rawData)
console.log(data)
console.log('-------------------------')
}
现在,我想测试api调用是否成功并且读取的数据是否正确。 为此,我尝试模拟data.json,但在运行测试时,始终未定义fileSystem.readFileSync('../ shoppinglist / data.json')。所以我想当它加载应用程序时,它会以某种方式忽略我的../ shoppinglist / data.json
的模拟数据describe('Get for all Lists with entries', () => {
it('should return a list with 2 entries without items', async () => {
jest.mock('../shoppinglist/data.json', () => ({
"data" : [
{
"id": 0,
"name": "filled shopping list",
"location": "lidl",
"targetDate": "22.03.1986",
"priority": 1,
"isFinished": false,
"items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
]
}, {
"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 {app} = require(appPath)
let res
res = await request(app)
.get(baseUrl)
expect(res.statusCode).toEqual(200)
expect(res.body.data).toHaveLength(2)
expect(res.body[0]).toEqual(expect.not.objectContaining({"items": ["vodka"]}))
})
})
我也尝试在测试中模拟fs,但我想这样不起作用
尝试后进行新编辑
我现在已经在测试中尝试过这个
const fs = require( 'fs')
jest.mock('fs')
describe('Get for all Lists with entries', () => {
it('should return a list with 2 entries without items', async () => {
fs.writeFileSync.mockClear();
fs.readFileSync.mockReturnValue('X')
const {app} = require(appPath)
let res
res = await request(app)
.get(baseUrl)
expect(res.statusCode).toEqual(200)
expect(res.body.data).toHaveLength(2)
expect(res.body[0]).toEqual(expect.not.objectContaining({"items":
["vodka"]}))
})
})
但是仍然,当通过以下方式调用app.js时
const {app} = require(appPath)
let res
res = await request(app)
.get(baseUrl)
readUpdateData方法始终在未定义的rawData位置,就像模拟永远不会被破坏一样。
function readUpdatedData(){
let rawData = fileSystem.readFileSync(dataFilePath)
data = JSON.parse(rawData)
module.exports = data
console.log(data)
console.log('-------------------------')
}
答案 0 :(得分:0)
我现在找到了解决方法
const mockReadFile = jest.spyOn(fs, 'readFileSync')
mockReadFile.mockImplementation(() => JSON.stringify({
"data" : [
{
"id": 0,
"name": "filled shopping list",
"location": "lidl",
"targetDate": "22.03.1986",
"priority": 1,
"isFinished": false,
"items": [{"count":1, "name": "vodka" }, {"count":1, "name": "vodka" }
]
}, {
"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" }
]
}
]}))
通过此操作,可以从模拟程序正确读取数据