我用 MongoDB 和 Mongoose 測驗了一些功能。對于測驗,我使用的是 Jest 和 mongo-memory-server。如果資料庫中已經存在具有該不和諧 id 的用戶,則該函式createUser(arg1, arg2) 應拋出TypeError 。
創建用戶(arg1,arg2)
async function createUser(disc_id, moodleToken) {
const profileData = await fetchUser(disc_id);
if (profileData) {
throw TypeError("The account already exist in the database!");
}
const newUser = new profileModel({
discord_id: disc_id,
moodle_token: moodleToken,
})
await newUser.save();
return {
userId: newUser._id
};
}
fetchUser(disc_id)回傳是否找到具有相同 discord id 的用戶。
在使用 Jest 進行測驗時,我創建了以下測驗,它通過了就好了:
it("Should create a new user", async () => {
const discord_id = "3452357445";
const moodle_token = "34ffDSE8439Ujfe8f3jj";
const { userId } = await createUser(discord_id, moodle_token);
const user = await profileSchema.findById(userId);
expect(user.discord_id).toEqual(discord_id);
expect(user.moodle_token).toEqual(moodle_token);
})
現在我想測驗在嘗試使用相同的不和諧 id 創建新用戶時是否拋出TypeError,我嘗試了以下操作但沒有成功:
describe("Error when", () => {
it("an existing matches discord id", async () => {
const discord_id = "3452357445";
const moodle_token = "34ffDSE8439Ujfe8f3jj";
await createUser(discord_id, moodle_token)
await expect(async () => {
createUser(discord_id, moodle_token);
}).rejects.toThrow(TypeError("The account already exist in the database!"))
})
})
運行測驗時,這是控制臺的輸出:
FAIL test/manageUserDB.test.js
Create new user
? Should create a new user (66 ms)
Error when
? an existing matches discord id (3 ms)
● Create new user ? Error when ? an existing matches discord id
TypeError: The account already exist in the database!
11 |
12 | if (profileData) {
> 13 | throw TypeError("The account already exist in the database!");
| ^
14 | }
15 | const newUser = new profileModel({
16 | discord_id: disc_id,
at createUser (BoodleDB/manageUserDB.js:13:15)
at Object.<anonymous> (test/manageUserDB.test.js:29:13)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 0.6 s, estimated 1 s
Ran all test suites matching /.\/test/i.
編輯
function fetchUser (disc_id) {
return profileModel.findOne({ discord_id: disc_id });
}
uj5u.com熱心網友回復:
呼叫 createUser 時需要等待。
await expect(async () => {
await createUser(discord_id, moodle_token);
}).rejects.toThrow(TypeError("The account already exist in the database!"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453594.html
