【发布时间】:2021-10-26 23:31:13
【问题描述】:
我开始在 nestjs 中编写端到端测试。连第一个简单的测试都失败了。
describe('Authentication system', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/(POST)', () => {
const email = 'khfkjdhsf@hot';
return request(app.getHttpServer())
.post('/signup')
.send({ email, password: 'kasdhfkjdhfkj' })
.expect(201)
.then((res) => {
const { id, email } = res.body;
expect(id).toBeDefined();
});
});
});
这是控制器:
@Post('/signup')
async createUser(@Body() body: CreateUserDto, @Session() session: any) {
const user = await this.authService.signUp(body.email, body.password);
session.userId = user.id;
return user;
}
这是 authService.signup:
async signUp(email: string, password: string) {
const users = await this.usersService.find(email);
if (users.length) {
throw new BadRequestException('Email in use');
}
const salt = randomBytes(16).toString('hex');
const hash = (await scrypt(password, salt, 64)) as Buffer;
const result = salt + '.' + hash.toString('hex');
const user = await this.usersService.create(email, result);
return user;
}
我在 bootstrap() 中使用 cookie-session 进行身份验证:
app.use(
cookieSession({
keys: ['anything'],
}),
);
当我向/signup 发送帖子请求时,一切正常。我相信测试逻辑是正确的。我在 stackoverflow 上找不到答案。
我在上述错误下也收到此错误:“Expected 201, 500 Internal Server Error”
【问题讨论】:
-
你能显示你尝试设置
userId的代码吗? -
你如何验证用户身份
-
您确定可以在测试环境中使用快速会话吗?这可能是原因。尝试模拟会话部分。
标签: typescript testing jestjs nestjs integration-testing