[英]Unit testing JavaScript which calls a function only if it exists, with Jest
[英]Unit testing classes with expo sqlite calls in jest
在学习对我的 expo/react-native 应用程序进行单元测试时遇到问题。 我将如何在此类中对向商店添加交易进行单元测试:
export default class TransactionsStore {
@observable _transactions = [];
constructor(rootStore) {
this.rootStore = rootStore;
}
@action addTransaction(t, db) {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO transactions (categoryId, description, date, amount, currencyCode, isReported) VALUES (?,?,?,?,?,?);',
[t.category, t.description, t.date, t.amount, t.currency.code, t.report],
(tx, result) => { t.id = result.insertId; }
);
}, error => alert(error));
this.reloadTransactions(db);
}
}
回调中的所有回调都使这变得非常困难。 我想我必须以某种方式模拟db.transaction
但我不知道如何以这种方式将假(tx, result)
放入executeSql
嵌套函数中。
能够通过一些想法来解决这个问题:
var sqlResult = { insertId: 1, rows: { _array: [] } };
const tx = { executeSql: jest.fn((query, sub=[], func=()=>true) => func({}, sqlResult)) };
const db = { transaction: jest.fn((func) => func(tx)) };
const rootStore = { db: db } };
describe('TransactionsStore', () => {
const store = new TransactionsStore(rootStore);
it('mocks sql', () => {
expect(tx.executeSql.mock.calls.length).toBeGreaterThan(0);
});
});
谈论大脑锻炼! 这样我就可以在测试之间操作sqlResult
来伪造来自 sql 调用的一些数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.