角度测试未调用期望,导致"规范没有期望"



我有对我的后端进行HTTP调用的服务,我正在尝试测试它是否会得到用户的响应,在运行测试时,即使我在订阅中有一个,我也得到了一个Spec has no expectation。除 2 外,所有这些测试都通过了SPEC HAS NO EXPECTATION

这是我的代码:

describe('Auth Service Testing', () => {
let httpClientSpy: { get: jasmine.Spy };
let authServ: AuthService;
let authAct: AuthActions;
let userAct: UserActions;
let checkoutAct: CheckoutActions;
let productAct: ProductActions;
let store: Store<any>;
let localStorageServ: LocalStorageService;
let authResponse;
const expectedUserResponse = {
users: [],
count: 25,
current_page: 1,
pages: 2
};
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
authServ = new AuthService(
<any>httpClientSpy,
authAct,
userAct,
checkoutAct,
productAct,
store,
localStorageServ
);
});
it('should get users response', () => {
httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));
authServ.authorized().subscribe((users) => {
authResponse = users;
expect(users).toEqual(jasmine.objectContaining({ users: [] }));
});
});
it('should equal to expected users response', () => {
expect(authResponse).toEqual(expectedUserResponse);
});
it('should return null if theres an error', () => {
httpClientSpy.get.and.returnValue(asyncError(expectedUserResponse));
authServ
.authorized()
.subscribe(() => {}, (error) => expect(error).toBe(null));
});
});

另外,我遵循了角度HTTP测试指南角度测试 我想知道这是一个错误还是其他什么。

业力结果:

Auth Service Testing
SPEC HAS NO EXPECTATIONS should return null if there's an error
SPEC HAS NO EXPECTATIONS should get users response
should equal to expected users response

更新

缺少的代码是这个expect(httpClientSpy.get.calls.count()).toBe(1);这很奇怪,我认为这个调用会发出一个 http get 请求httpClientSpy.get.and.returnValue(asyncError(expectedUserResponse));

但是在指南上的错误测试中,他们没有这个。有人可以阐明这一点吗?

来自朝鲜的爱。 <3

使用订阅对可观察量进行单元测试确实很困难。在许多边缘情况下,单元测试将通过,但应该失败。即使您将done()回调与 finiazlier 或错误处理程序一起使用。

每当可观察量只发出一个预期结果时,您应该改用承诺。

it('should get users response', async () => {
httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));
const users = await = authServ.authorized().toPromise();
expect(users).toEqual(jasmine.objectContaining({ users: [] }));
});

每当可观察量发出多个值时,您都可以转换为数组并仍然使用 promise。

it('should get users response', async () => {
httpClientSpy.get.and.returnValue(asyncData(expectedUserResponse));
const users = await = authServ.authorized().pipe(
toArray()
).toPromise();
expect(users).toEqual(jasmine.objectContaining([{ users: [] }]));
});

toPromise()的优点是它总是可以解决。即使可观察量未发出任何值,如果在可观察量中抛出任何未捕获的错误,它也不会通过单元测试。

最新更新