我知道之前有人问过这个问题,但是当我运行服务测试功能时,我在 Nestjs 中遇到了这个错误
这是我的服务代码
用户服务.ts
import { Injectable,HttpException, HttpCode, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { UserRegisterAC } from '../application/userRegisterAC';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>) {}
async allUsersList(): Promise<User[]> {
var users = this.userRepository.find();
if(users==null){
throw new HttpException("Users not found",HttpStatus.NOT_FOUND)
}else{
return users as unknown as User[];
}
}
async create(userDTO: UserRegisterAC): Promise<User> {
const user = new User();
user.name = userDTO.name;
user.phoneNo = userDTO.phoneNo;
return this.userRepository.save(user);
}
}
用户.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should return user array', async() => {
const result = [{id:1,name:'mayur',phoneNo:'9998814695'}];
// @ts-ignore
jest.spyOn(service,'allUsersList').mockImplementation(() => result);
expect(await service.allUsersList()).toBe(result);
});
});
在这个文件中,我想测试返回用户数组的用户服务中的 allUserlist 函数。用户实体包含 id、name 和 phoneNo。当我运行测试时,我收到了类似的错误
Cannot spyOn on a primitive value; undefined given
17 | const result = [{id:1,name:'mayur',phoneNo:'9998814695'}];
18 | // @ts-ignore
> 19 | jest.spyOn(service,'allUsersList').mockImplementation(() => result);
| ^
20 | expect(await service.allUsersList()).toBe(result);
21 | });
22 | });
这是我的笑话配置
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"automock": true
}
我尝试了一切请给一些建议