Mah*_*ard 18 api unit-testing reactjs jestjs
我开玩笑地为我的api编写了测试。我在测试文件中添加了调用我的api的函数,如下所示:
import AuthManager from "../Client/Modules/Auth/AuthManager";
Run Code Online (Sandbox Code Playgroud)
并如下使用:
test("login api resolves true", () => {
return expect(AuthManager.login("test", "test")).resolves.toMatchObject(
expect.objectContaining({
accessToken: expect.any(String),
email: expect.any(String),
expiresIn: expect.any(Number),
refreshToken: expect.any(String),
userFullName: expect.any(String),
userId: expect.any(Number)
})
);
});
Run Code Online (Sandbox Code Playgroud)
我的测试通过了,但是出现以下错误:
错误:未实现:window.alert
如何解决这个问题呢 ?
Bri*_*ams 12
在默认的测试环境为Jest是一个类似浏览器所提供的环境jsdom。
jsdom实现了实际浏览器将提供的大部分功能(包括全局window对象),但并未实现所有功能。
专门为这种情况下,jsdom没有实现window.alert,而是抛出Error时,它被称为可以在源代码中可以看出这里。
只要您知道代码为什么要启动,alert并且知道测试除了之外Error还可以正常运行,那么您可以Error通过为空提供以下实现来抑制window.alert:
test("login api resolves true", () => {
const jsdomAlert = window.alert; // remember the jsdom alert
window.alert = () => {}; // provide an empty implementation for window.alert
return expect(AuthManager.login("test", "test")).resolves.toMatchObject(
expect.objectContaining({
accessToken: expect.any(String),
email: expect.any(String),
expiresIn: expect.any(Number),
refreshToken: expect.any(String),
userFullName: expect.any(String),
userId: expect.any(Number)
})
); // SUCCESS
window.alert = jsdomAlert; // restore the jsdom alert
});
Run Code Online (Sandbox Code Playgroud)
我如何解决此问题的window.alert方法实际上是将测试文件顶部的方法定义为一个玩笑。这应该适用于任何window方法(就我而言,我实际上是在测试window.open)。
确保调用mockClear()您的测试,因为这是一个全局对象,并且该调用将在测试之间持续存在。
window.alert = jest.fn();
test("login api resolves true", () => {
window.alert.mockClear();
/* ... */
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4920 次 |
| 最近记录: |