javascript - 用 jest 在其他文件中声明的测试函数
问题描述
我有一个测试功能的问题。函数在app.js中定义,测试文件是app.test.js 怎么导入函数,以便测试?我的目标是仅对功能进行单元测试,而不对 app.js 中的所有其他内容进行单元测试
应用程序.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)
})
})
我猜这需要/导入有问题。但我只能在这里使用require。
解决方案
需要该getNewestId
功能并像这样测试它:
const { getNewestId } = require("./app");
const testData = [
{
"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" }]
}
];
describe("getNewestId from Valid array", () => {
it("should return id 3", () => {
expect(getNewestId(testData)).toEqual(3);
})
});
如果您想使用单元测试,请确保您测试的函数是pure。在您熟悉了这一点之后,考虑在其他级别上测试您的应用程序,例如,编写将影响您的 API 的测试;)
推荐阅读
- javascript - Storybook w/ react-router - 你不应该在外面使用
- java - How to read text files(.txt) from file system using reader and pass each file's text to processor spring batch?
- opencv - 用于轨迹估计的卡尔曼滤波器实现中 opencv predict() 的控制矩阵?
- c - 从 cc 命令行转换为 CMakeLists.txt
- laravel - 生成 API 和 laravel 护照
- laravel - Limiting laravel pagination center to 3
- c# - Xamarin 更改 Grid 中每一行的 RowHeight
- django - 使用 django 权限。IsAuthenticatedOrReadOnly 和令牌认证
- python - 将一个数据框中的一列与不同数据框中的其他两列进行比较?
- vba - How to reference a primary key in Ms Access VBA behind a report