我尝试了很多方法来用玩笑来模拟通用函数,但没有成功。这是我认为正确的方法:
interface ServiceInterface {
get<T>(): T;
}
class Service implements ServiceInterface {
get = jest.fn(<T>(): T => {
throw new Error("Method not implemented.");
});
}
Run Code Online (Sandbox Code Playgroud)
编译时会抛出以下错误:
error TS2416: Property 'get' in type 'Service' is not assignable to the same property in base type 'ServiceInterface'.
Type 'Mock<{}, any[]>' is not assignable to type '<T>() => T'.
Type '{}' is not assignable to type 'T'.
Run Code Online (Sandbox Code Playgroud)
你能告诉我正确的方法吗?
谢谢
我在我的 Nodejs 应用程序中使用 sendGrid 电子邮件
https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail
基本上,当用户注册时,我会发送一封欢迎电子邮件
但是当我为用户注册编写测试时,我想模拟 sendgrid 发送函数。我怎么能开玩笑呢。或者关于如何测试注册 api 的任何建议
我尝试axios像这样在测试文件中模拟模块
// mycomponent.test.js
import axios from 'axios';
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve({ data: 'data' })),
default: jest.fn(() => Promise.resolve({ data: 'data' })),
}));
Run Code Online (Sandbox Code Playgroud)
但是,当我将其添加jest.mock('axios')到测试文件后,出现了这样的错误。
TypeError: (0 , _axios.default) is not a function
55 | this.props.updateGlobalLoading(true);
56 |
> 57 | axios({
| ^
58 | method: 'get',
59 | url: '/v1/api/portal-xml-list',
60 | }).then((res) => {
Run Code Online (Sandbox Code Playgroud)
那么,我应该如何解决这个问题,而我却想为axios模拟设置任何东西呢?
谢谢!
jestjs ×3
axios ×1
javascript ×1
mocking ×1
node.js ×1
sendgrid ×1
ts-jest ×1
typescript ×1
unit-testing ×1