我在我的电子商务软件上使用jest,这样我也可以在端到端测试时进行渲染测试(支持主题,这就是为什么)。
但我目前只是在测试一些mongoose功能,当我试图保存文档时,它给出了这个错误:Error: Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.
我注意到,当我使用await doc.save();删除行时,它不会给出这个错误。所以我认为它与async/await有关,但我找不到它。
package.json
"jest": {
"automock": false,
"moduleDirectories": [
"node_modules"
],
"testPathIgnorePatterns": [
"node_modules",
".idea",
"public"
],
"collectCoverage": true,
"coverageThreshold": {
"global": {
"branches": 5,
"lines": 40,
"functions": 25,
"statements": -1000
}
},
"setupTestFrameworkScriptFile": "./setupJest.js",
"coverageDirectory": "coverage",
"globalSetup": "./globalSetupJest.js"
}globalSetupJest.js
const Mongoose = require('mongoose').Mongoose;
const mongoose = new Mongoose();
const Mockgoose = require('mockgoose').Mockgoose;
const mockgoose = new Mockgoose(mongoose);
const {promisify} = require('util');
module.exports = async () => {
try {
await mockgoose.prepareStorage();
promisify(mongoose.connect);
await mongoose.connect('mongodb://localhost/test')
mongoose.connection.on('connected', () => {
console.log('db connection is now open');
});
} catch (e) {
console.log('error in setting up mockgoose', e);
}
};Product.test.js
describe('Product', () => {
const index = require('./index');
const productSchema = require('./model');
const Product = mongoose.model(index.modelName, productSchema);
describe('Instance Functionality', () => {
let baseProductObj;
let localProduct;
beforeEach(async () => {
baseProductObj = {
ean: 123456789,
title: 'Test product',
description: 'Test description',
stock: {
amount: 5,
track: true
},
pricing: {
cost: 5,
price: 10
},
url: 'test-product'
};
localProduct = new Product(baseProductObj);
try {
return await localProduct.save();
} catch (e) {
console.log('error in beforeEach', e);
}
});
describe('.reduceStock', () => {
test('Should decrease the stock by a default of 1', async () => {
try {
localProduct.reduceStock();
await localProduct.save();
} catch (e) {
console.log('error in saving localProduct', e);
}
expect(localProduct.stock.amount).toEqual(4);
});
});
});
});发布于 2018-07-14 10:51:16
我已经有一段时间没有使用JEST了,但我认为异步代码需要“完成”回调。
你的代码应该是:
test("Should decrease the stock by a default of 1", async (done) => {
try {
localProduct.reduceStock();
await localProduct.save();
done();
} catch (e) {
console.log("error in saving localProduct", e);
}
expect(localProduct.stock.amount).toEqual(4);
});如果不起作用,请尝试返回文档。
await localProduct.save();应该是
return await localProduct.save();发布于 2018-07-14 04:13:38
您可以通过添加以下内容在测试中指定更大的超时:
jest.setTimeout(50000);https://stackoverflow.com/questions/51331620
复制相似问题