gpt4 book ai didi

javascript - 单元测试数据库查询

转载 作者:行者123 更新时间:2023-11-30 19:59:29 25 4
gpt4 key购买 nike

问题作为单元测试的初学者,我最近遇到的一个问题是处理数据库使用量很大的类。

使用的技术:Typescript、SinonJS、Node-Postgres 和 Jest

示例:对于给定的函数

public async insertUserDetails() {

const confirmationCode = this.generateConfirmationCode();

try {

await this.db.query({
text: 'INSERT INTO users (firstname, lastname, email, password, registration_date, confirmation_code) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
values: [this.firstname, this.lastname, this.email, this.password, this.registrationDate, confirmationCode]
});


} catch (error) {

throw error;

}

}

问题:合适的单元测试是否是为了确保使用正确的 sql 调用 db.query() 函数,如下所示?或者这会被视为浪费时间和脆弱测试吗?

test("should format correct sql", async () => {

//Test Setup
const user = new User({
firstname: "John",
lastname: "doe",
email: "email@example.com",
password: "some_password_hash",
registrationDate: "some_random_date",
});

//Mocks
const queryStub = sinon.stub(user.db, "query");
const confirmationCode = sinon.stub(user,'generateConfirmationCode').returns("48fsakb8a-cfjdab");

const sampleQuery = {
text: 'INSERT INTO users (firstname, lastname, email, password, registration_date, confirmation_code) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
values: [user.firstname, user.lastname, user.email, user.password, user.registrationDate, confirmationCode]
}

//Preform
await user.insertUserDetails();

//Assert
sinon.assert.calledWith(queryStub, sampleQuery);


});

或者我应该跳过对这些类型的函数和类的所有单元测试,并设置一个集成测试数据库并通过集成测试来测试这些用例吗?

这是一个非常简化的示例,因为我没有进入测试数据库事务,但是测试事务变成了一个更大的蠕虫病毒库,因为要执行多个查询。

感谢您的帮助!这让我发疯 -__-

最佳答案

Would a suitable unit test be to make sure that the db.query() function is called with the correct sql such as the following?

如果您专注于制作 db.query,那么您尝试做的不是单元测试。然后它变成了一个集成测试。这里您要测试的单元是 insertUserDetails。所以你关注这个函数的行为。您可以测试的是:1. 使用正确的参数调用了 db.query(希望 this.db 可以被模拟)2. 如果 db.query 抛出异常,那么您的 catch block 将被执行并抛出您的异常。

同样,您应该尝试为覆盖query 函数的this.db 类编写单元测试。

因此,一旦您确定两个单元都已正确覆盖,那么这将是一个好的开始。

现在,如果您可以选择一次编写集成测试,您可以在其中使用某种内存数据库或者可能是您可以随意使用的真实数据库,那么继续这样做,您可以不编写单元测试共。

希望这对您有所帮助。

关于javascript - 单元测试数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53550538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com