Jest spyOn已接电话数:0



我正在为组件编写Jest以确保handleError将被执行。

UserService定义为:

export class UserService {
constructor(private http: HttpClient, private errorHandleService: ErrorHandlerService) {
}
login(user, password) {
this.loadingLogin.next(true);
return this.http.post(this.loginUrl, JSON.stringify({
user,
password
}), this.httpOptions)
.pipe(
catchError(error => this.errorHandleService.handleError('login', error)),
finalize(() => this.loadingLogin.next(false))
);
}
}

我已经删除了这里大部分不必要的代码。这是我的测试部分。

describe('UserService', () => {
let httpMock;
let errorHandleServiceMock;
let userService;
beforeEach(() => {
httpMock = {
post: jest.fn()
};
errorHandleServiceMock = {
handleError: jest.fn()
};
userService = new UserService(httpMock, errorHandleServiceMock);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Login', () => {
test('should throw an error when login', () => {
const user = 'user';
const password = 'password';
const error = 'error';
const response = {};
jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));
const errorSpy = jest.spyOn(errorHandleServiceMock, 'handleError');
userService.login(user, password).subscribe(() => {
});
expect(errorSpy).toHaveBeenCalled();
});
});

它不工作,我得到以下错误:

Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls:    0

实际http请求模拟的返回类型错误

jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));

改为

jest.spyOn(httpMock, 'post').mockReturnValue(throwError(error));

和您期望的断言应该弹出。

解决方案在这里;)

test('should throw an error when login', () => {
const user = 'user';
const password = 'password';
const error = new Error('error');
const response = {};
jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));
const errorSpy = jest.spyOn(errorHandleServiceMock, 'handleError');
try {
userService.login(user, password).subscribe(() => {
});
} catch (e) {
expect(errorSpy).toHaveBeenCalled();
}
});

最新更新