gpt4 book ai didi

javascript - 什么被认为是测试返回 http observable 的方法的正确方法?

转载 作者:行者123 更新时间:2023-11-30 14:10:11 25 4
gpt4 key购买 nike

我有一个 TypeScript 项目,我想将其部署为 JS NPM 包。这个包使用 rxjs ajax 函数执行一些 http 请求。现在我想为这些方法编写测试。

有时我有这样的方法(简化!):

getAllUsers(): Observable<AjaxResponse> {
return ajax.get(this.apiUrl + '/users');
}

我了解基本测试,例如使用 spyOn 我可以模拟来自服务器的响应。但是我将如何实际测试 http 请求?

jasmine 的文档说我不能在 it 部分进行异步工作,但在 beforeEach 中:https://jasmine.github.io/tutorials/async

这是测试 API 的正确方法吗?

let value: AjaxResponse;
let error: AjaxError;

beforeEach((done) => {

const user = new UsersApi();
user.getAllUsers().subscribe(
(_value: any) => {
value = _value;
done();
},
(_error: any) => {
error = _error;
done();
}
);

});

it("should test the actual http request", () => {

// Test here something
// expect(value).toBe...
// expect(error).toBe...

});

我想不出另一种方法来完成异步工作...

最佳答案

您需要模拟 ajax.get 以返回一个 Observable,该 Observable 会发出您想要测试的值。

这取决于 ajax 在包含 user.getAllUsers 方法的文件中的声明方式。

如果 UsersApi()ajax 传递给它(纯函数样式),那将是理想的,因为那样你就可以做这样的事情:

例如

class UsersApi {

public ajax;

constructor(ajax) {
this.ajax = ajax;
}

getAllUsers() {
return this.ajax.get(....)
}

}

编辑:传递依赖项(也称为依赖项注入(inject))是使此类模块更易于测试的一件事 - 考虑这样做吧!

然后你可以很容易地像这样模拟你的测试:

  const someSuccessfulResponse = ...
const someFailedResponse = ...

const ajaxWithSuccess = {
get:jest.fn(() => of(someSuccessfulResponse))
}

const ajaxWithFailed = {
get:jest.fn(() => throwError(someFailedResponse))
}

describe('my test suite',() => {

it("should test a successful response", (done) => {

const user = new UsersApi(ajaxWithSuccess);
user.getAllUsers().subscribe(d => {
expect(d).toBe(someSuccessfulResponse);
done();
});

});

it("should test a failed response", (done) => {

const user = new UsersApi(ajaxWithFailed);
user.getAllUsers().subscribe(null,error => {
expect(d).toBe(someFailedResponse);
done();
});

});

});

注意:您不要想要测试实际的 API 请求。 您想测试您的代码是否成功处理了您认为它可以接收到的任何 API 响应。想一想,如果您的 API 始终能够正确处理失败的 API 响应,您将如何测试您的代码是否正确处理了失败的 API 响应返回 200 秒?

编辑#27:当我运行 jest 时,上面的代码对我来说工作正常,不完全清楚为什么 jasmine(不是 jest 在 jasmine 上运行?)说它不能在 it 中执行异步> 的。在任何情况下,您都可以更改上面的代码以在 beforeEach 中设置所有内容,并在 it 中执行您的 expect

关于javascript - 什么被认为是测试返回 http observable 的方法的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54608492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com