nob*_*are 4 javascript unit-testing typescript reactjs jestjs
我有一个以前创建的.js文件,它模拟了我们的一些函数用于jest测试目的.我正在将其迁移到.ts文件:
Server.ts
const Server = jest.genMockFromModule('../Server');
Server.getAsync = Server.default.getAsync;
// other REST-ful functions here
export default Server;
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
类型"{}"上不存在属性"getAsync"
类型"{}"上不存在属性"默认"
然后,在相应的测试文件中:
MyComponent.test.ts
import Server from 'path/to/Server';
jest.mock('path/to/Server');
const dispatchMock = jest.fn();
const getStateMock = jest.fn();
describe('MyComponent.someFunction', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('Does the right stuff', () => {
Server.getAsync.mockReturnValueOnce(Promise.resolve([{ key: 'value' }]));
dispatchMock.mockImplementationOnce((promise) => promise);
dispatchMock.mockImplementationOnce();
return someFunction()(dispatchMock)
.then(() => {
expect(Server.getAsync).toHaveBeenCalledTimes(1);
expect(Server.getAsync.mock.calls[0][0]).toBe('something');
});
});
});
Run Code Online (Sandbox Code Playgroud)
我收到了错误 dispatchMock.mockImplementationOnce()
期望1个参数,但得到0.(方法)jest.MockInstance <{}>.mockImplementationOnce(fn:(... args:any [])=> any):jest.Mock <{}>
...上 Server.getAsync.mockReturnValueOnce
属性'mockReturnValueOnce'在类型'上不存在(url:string,baseRoute?:string | null,loadingGenerator?:( isLoading:boolean)=> {type:strin ...'.
......等等 Server.getAsync.mock
属性'mock'在类型'上不存在(url:string,baseRoute?:string | null,loadingGenerator?:( isLoading:boolean)=> {type:strin ...'.
我已经在这方面狠狠地敲了一下,所以任何帮助都会非常感激.
UPDATE
好的,我添加as any到Server.ts文件第一行的末尾,所以现在它看起来像:
const Server = jest.genMockFromModule('../Server') as any;
Run Code Online (Sandbox Code Playgroud)
这摆脱了第一组错误.仍然面对我的.test.ts文件中的错误.
更新2
我注意到,当我运行实际的jest测试时,即使有TypeErrors,它们都会通过.这些问题似乎与实际测试无关.
nob*_*are 17
我自己修好了.我让它工作的方式是将任何调用转换Server.getAsync为特定的jest模拟类型.
let getAsyncMock = Server.getAsync as jest.Mock
Run Code Online (Sandbox Code Playgroud)
要么
let getAsyncMock = <jest.Mock>(Server.getAsync)
Run Code Online (Sandbox Code Playgroud)
这摆脱了我的错误.
在@nobleare 响应之后……一个很好的更新是将您的模拟实现包装到 中beforeAll并将其清除到beforeEach块中:
import { AnalyticsApi } from "../../api/src";
jest.mock("../../api/src");
describe('...', () => {
beforeAll(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
listPolicies: jest.fn().mockResolvedValue('promiseValue')
}));
});
beforeEach(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockClear();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7242 次 |
| 最近记录: |