Ktr*_*000 4 integration-testing express typescript supertest jestjs
我正在使用 MongoDB 和 Mongoose 测试 typescript-express ap。对于此测试,我使用 jest 和 mongo-memory-server。我可以测试插入新文档并将现有文档检索到数据库中,但当文档不存在时我无法捕获错误。
const getUserByEmail = async (email: string): Promise<UserType> => {
try {
const user = await User.findOne({ email });
if (!user) {
const validationErrorObj: ValidationErrorType = {
location: 'body',
param: 'email',
msg: 'User with this email does not exist!',
value: email,
};
const validationError = new ValidationError('Validation Error', 403, [
validationErrorObj,
]);
throw validationError;
}
return user;
} catch (err) {
throw new Error(err);
}
};
let mongoServer: any;
describe('getUserByEmail', (): void => {
let mongoServer: any;
const opts = {}; // remove this option if you use mongoose 5 and above
const email = 'test@mail.com';
const password = 'testPassword';
const username = 'testUsername';
beforeAll(async () => {
mongoServer = new MongoMemoryServer();
const mongoUri = await mongoServer.getConnectionString();
await mongoose.connect(mongoUri, opts, err => {
if (err) console.error(err);
});
const user = new User({
email,
password,
username,
});
await user.save();
});
afterAll(async () => {
mongoose.disconnect();
await mongoServer.stop();
});
it('fetching registered user', async (): Promise<void> => {
const user = await getUserByEmail(email);
expect(user).toBeTruthy();
expect(user.email).toMatch(email);
expect(user.password).toMatch(password);
expect(user.username).toMatch(username);
}, 100000);
it('fetching non registered user', async (): Promise<void> => {
const notRegisteredEmail = 'some@mail.com';
expect(await getUserByEmail(notRegisteredEmail)).toThrowError();
}, 100000);
});
Run Code Online (Sandbox Code Playgroud)
在遇到同样的问题后,这对我有用:
await expect(asyncFuncWithError()).rejects.toThrow(Error)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4219 次 |
| 最近记录: |