【发布时间】:2020-09-04 03:59:48
【问题描述】:
This is my controller class(usercontoller.ts) i am trying to write junit test cases for this class
import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';
import { UserDto } from '../shared/interfaces/dto/user.dto';
import { UserService } from './user.service';
async updateUser(@BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {
try {
if (!user.id) {
throw new BadRequestException('User Id is Required');
}
return await this.userService.updateUser(user);
} catch (e) {
throw e;
}
}
这是我的 TestClass(UserContollerspec.ts) 在运行我的测试类时出现错误“无法监视 updateUser 属性,因为它不是函数;未定义给定。 得到错误。 但是,当我使用 spyOn 方法时,我不断收到 TypeError: Cannot read property 'updateuser' of undefined:
*似乎 jest.spyOn() 在我做错的地方无法正常工作。 有人可以帮助我。我正在传递的论点?
jest.mock('./user.service');
describe('User Controller', () => {
let usercontroller: UserController;
let userservice: UserService;
// let fireBaseAuthService: FireBaseAuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService]
}).compile();
usercontroller = module.get<UserController>(UserController);
userservice = module.get<UserService>(UserService);
});
afterEach(() => {
jest.resetAllMocks();
});
describe('update user', () => {
it('should return a user', async () => {
//const result = new UpsertUserDto();
const testuser = new UpsertUserDto();
const mockDevice = mock <Promise<UpsertUserDto>>();
const mockNumberToSatisfyParameters = 0;
//const userservice =new UserService();
//let userservice: UserService;
jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);
expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);
it('should throw internal error if user not found', async (done) => {
const expectedResult = undefined;
****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****
await usercontroller.updateUser(testuser)
.then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))
.catch((error) => {
expect(error.status).toBe(503);
expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503}); done();
});
});
});
});
【问题讨论】:
标签: javascript node.js jestjs nestjs