我有一個簡單的快速后端,我想測驗它。當/messages使用 GET命中時,后端僅回傳一個訊息陣列。
注意:我知道可能有一個簡單的修復,因為我對 node.js 世界相對較新,并且以前主要在 Python 環境中作業過。所以,請提供帶有解釋的答案。
這是我的package.json:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "index.js",
"scripts": {
"dev": "nodemon server.js",
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1"
},
"devDependencies": {
"jest": "^27.3.1",
"supertest": "^6.1.6"
}
}
注意事項:
"type": "module".- 我正在使用 jest 和 supertest 來測驗啟用了 Express 的后端。
讓我們看看我的server.js樣子:
import app from './app.js'
const port = 3000
app.listen(port, () => console.log('app running'))
出于測驗目的,在 server.js 中,我只有啟動服務器的代碼。所有重要的代碼都在app.js.
import express from 'express'
import cors from 'cors'
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const messages = ['hello', 'hi', 'its working']
app.get('/messages', (req, res) => {
res.send(messages)
})
export default app
注意事項:
export default app
在我繼續向您展示我的 server.test.js 之前,讓我們看看我的目錄結構。
├── app.js
├── package.json
├── package-lock.json
├── server.js
└── tests
└── server.test.js
1 directory, 5 files
現在,這是我的server.test.js:
import app from '../app'
import supertest from 'supertest'
const requestWithSupertest = supertest(app);
describe('Messages Endpoints', () => {
it('GET /messages should show all messages', async () => {
const res = await requestWithSupertest.get('/messages');
expect(res.status).toEqual(200);
expect(res.type).toEqual(expect.stringContaining('json'));
expect(res.body).toHaveProperty('messages')
});
});
注意事項:import app from '../app'。我正在從名為 app.js 的檔案中匯入應用程式,該檔案位于樹中上方的一個目錄,如上面的tree輸出所示。
現在我已經設定好了一切,當我繼續呼叫測驗時。我收到了 jest runner 拋出的錯誤。我洗掉了一些輸出以顯示主要錯誤:
FAIL tests/server.test.js
● Test suite failed to run
Jest encountered an unexpected token
[output trimmed...]
Details:
/efs/repos/vueandauth/backend/tests/server.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import app from '../app';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.149 s
Ran all test suites.
我在 Stackoverflow 上搜索了其他問題,其中一些建議"type": "module"在 package.json 中做一個。我已經做過了。為什么我會收到此錯誤以及如何解決此問題?
uj5u.com熱心網友回復:
對于ECMAScript 模塊的玩笑支持,您可以查看此GitHub 問題
為了轉譯匯入,您可以使用 Babel ( jest docs )。
安裝巴貝爾:
yarn add --dev babel-jest @babel/core @babel/preset-env
通過創建babel.config.js或添加 babel 配置.babelrc
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
GitHub 上的作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350164.html
上一篇:如果要將多列中的值與命名范圍內的相應值進行比較,應使用哪個公式?
下一篇:axios傳遞引數如何獲取請求?
